Regex pattern for function call

I have defined the following template to parse our own user interface for a function that is: <functionName>[<arg1>, <arg2>, ..]

and a template:
([a-zA-Z0-9]+)\\[(([a-zA-Z0-9]+)(,([a-zA-Z0-9])+)*?)*?\\]

Now when I run this against the example function:, properCase[ARG1,ARG2]

I get the following output:

Total matches are: 5
Group number 0is: properCase[ARG1, ARG2]
Group number 1is: properCase
Group number 2is: ARG1
Group number 3is: ARG1
Group number 4is: ,ARG2

      

code:

        Matcher m = funcPattern.matcher("properCase[ARG1, ARG2]");
        System.out.println("Match found: " + m.matches());
        System.out.println("Total matches are: " + m.groupCount());
        if (m.matches())
        {
            for (int index= 0 ; index < m.groupCount(); index++)
            {
                System.out.println("Group number "+ index + "is: " +m.group(index));
            }
        }

      

How can I extract just the function name (like group 1) and the argument list (like group 2, group 3)? I cannot remove ,

from the group.

+3


source to share


2 answers


I can't use the regex you provided to match properCase[ARG1, ARG2]

, but to answer your question more generally, you should use non-capturing groups (?:your_regex)

so as not to include them in conjugate groups

EDIT:

If you are unmarried using the same regex to parse, consider this: split the string into function names and argument groups, and then split the argument group by a delimiter.



import java.util.regex.*
String regex="([a-zA-Z0-9]+)\\[([ ,.a-zA-Z0-9]+)\\]"
Pattern funcPattern = Pattern.compile(regex);
Matcher m = funcPattern.matcher("properCase[ARG1, ARG2, class.otherArg]");
        System.out.println("Match found: " + m.matches());
        System.out.println("Total matches are: " + m.groupCount());
        if (m.matches())
        {
            for (int index= 0 ; index <= m.groupCount(); index++)
            {
                System.out.println("Group number "+ index + "is: " +m.group(index));
            }
        }
println "Arguments: " + m.group(2).split(",");

      

Outputs:

Match found: true
Total matches are: 2
Group number 0is: properCase[ARG1, ARG2, class.otherArg]
Group number 1is: properCase
Group number 2is: ARG1, ARG2, class.otherArg
Arguments: [ARG1,  ARG2,  class.otherArg]

      

+2


source


Close the comma in your group to get around it.



([a-zA-Z0-9]+)\\[(([a-zA-Z0-9]+)(,)(([a-zA-Z0-9])+)*?)*?\\]

+1


source







All Articles