Raquel Romão Raquel Romão - 1 month ago 8
Java Question

Find comma in the parameters of a function using regex

I need to find the occurrence of a chain call functions, but must include the case where there is more than one parameter passed as (programming in java):

Tower.getType(i,j).initialPrice(f,g);

Tower.getType().initialPrice();

So far only managed to make the regex when there is only one parameter or no one:

[\w]+([.]+[\w]+[(]+[\w]*+[)]){2,}+[;]

Like:

Tower.getType().initialPrice();

object.function().function2().function3().function4().function5();

I trying this, but its not working:

[\w] + ([\.] + [\w] + [(] + [\w]* + ([\,] + [\w])* + [)]) {2,} + [;]

My code:

public static void checksMessageChain (String s) {
if (s!=null && s.matches("[\\w]+([\\.]+[\\w]+[(]+[\\w]*+[)]){2,}+[;]")) {
System.out.println("\nIts Message Chain for "+s+"\n");
splitMessageChain(s); // {0,} equivale a *
} else if (s!=null && s.matches("[\\w] + ([\\.] + [\\w] + [(] + [\\w]* + ([\\,] + [\\w])* + [)]) {2,} + [;]")) {
System.out.println("\nIts Message Chain for "+s+"\n");
splitMessageChain(s);
} else {
System.out.println("\nIts not Message Chain for "+s+"\n");
} }

Answer

I wouldn't bother with specifying the parameters and just use this :

\\w+(?:\\.\\w+\\([^)]*\\)){2,};

Note that this will fail if one String parameter contains a closing parenthesis, and it doesn't handle multi-line expressions.
As is usual for such a complex language, you'd better use a specialized parser. I have never used one, but a quick search reveals javaparser available on Github.

You can try it on regex101.

Comments