1

Here is the regex i used to extract the function name

Regex

^(\w+(\s+)?){2,}\([^!@#$+%^]*\)

Code

final static String functionNameRegex = "^(\\w+(\\s+)?){2,}\\([^!@#$+%^]*\\)";
final static String functionString = "public void render(int screenNo, String infoText){}";


final Pattern fnPattern = Pattern.compile(functionNameRegex, Pattern.CASE_INSENSITIVE | Pattern.COMMENTS);
final Matcher fnMatcher = fnPattern.matcher(functionString);

while (fnMatcher.find()) {
       System.out.println("Full match: " + fnMatcher.group(0));
       for (int i = 1; i <= fnMatcher.groupCount(); i++) {
             System.out.println("Group " + i + ": " + fnMatcher.group(i));
       }
}

But, it throws PatternSyntaxException. Not sure what's causing the problem here, as i am able to get the desired output in other languages.

Traces:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 30
^(\w+(\s+)?){2,}\([^!@#$+%^]*\)
                              ^
    at java.util.regex.Pattern.error(Pattern.java:1955)
    at java.util.regex.Pattern.clazz(Pattern.java:2548)
    at java.util.regex.Pattern.sequence(Pattern.java:2063)
    at java.util.regex.Pattern.expr(Pattern.java:1996)
    at java.util.regex.Pattern.compile(Pattern.java:1696)
    at java.util.regex.Pattern.<init>(Pattern.java:1351)
    at java.util.regex.Pattern.compile(Pattern.java:1054)
    at TestRegex.main(TestRegex.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

New to regex, assist me out in rechanging this regex to identify and group the parameter names.

1 Answer 1

4

You compile the regex with Pattern.COMMENTS and you have a # symbol inside the pattern. You need to escape it, else, it denotes the start of a comment.

Use

final static String functionNameRegex = "^(\\w+(\\s+)?){2,}\\([^!@\\#$+%^]*\\)";

See the Java demo.

Also, consider changing (\\w+(\\s+)?){2,} to (\\w+(?:\\s+\\w+)+) if you plan to match 2 or more space separated words (it will work much faster) (Group 1 will still hold the value before the parentheses).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. that helped. please provide input on re-changing this regex to capture the parameter names.
@surendhar_s See ideone.com/rujQfw, sorry, I am just not sure what you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.