Regex to find method calls

For qualified calls {i.e., calls in this form: [objectName|className].methodName(..) }, I've been using:

(\.[\s\n\r]*[\w]+)[\s\n\r]*(?=\(.*\))

When unqualified calls are present {i.e., calls in this form: methodName(..) }, I've been using:

(?!\bif\b|\bfor\b|\bwhile\b|\bswitch\b|\btry\b|\bcatch\b)(\b[\w]+\b)[\s\n\r]*(?=\(.*\))

Although, this will also find constructors.


I once had to figure out if a string contains a Java method call (including method names containing non-ASCII characters).

The following worked quite well for me, though it also finds constructor calls. Hope it helps.

/**
 * Matches strings like {@code obj.myMethod(params)} and
 * {@code if (something)} Remembers what's in front of the parentheses and
 * what's inside.
 * <p>
 * {@code (?U)} lets {@code \\w} also match non-ASCII letters.
 */
public static final Pattern PARENTHESES_REGEX = Pattern
        .compile("(?U)([.\\w]+)\\s*\\((.*)\\)");

/*
 * After these Java keywords may come an opening parenthesis.
 */
private static List<String> keyWordsBeforeParens = Arrays.asList("while", "for",
            "if", "try", "catch", "switch");

private static boolean containsMethodCall(final String s) {
    final Matcher matcher = PARENTHESES_REGEX.matcher(s);

    while (matcher.find()) {
        final String beforeParens = matcher.group(1);
        final String insideParens = matcher.group(2);
        if (keyWordsBeforeParens.contains(beforeParens)) {
            System.out.println("Keyword: " + beforeParens);
            return containsMethodCall(insideParens);
        } else {
            System.out.println("Method name: " + beforeParens);
            return true;
        }
    }
    return false;
}

Tags:

Java

Regex