正则表达式找到方法调用

Ali*_*lan 6 java regex

我想在给定的代码中找到任何方法调用.所以我用分号作为分隔符拆分代码.所以最后我有兴趣找到在给定代码中调用的方法的名称.我需要一个正则表达式来匹配方法调用模式.请帮忙!!

Mat*_*aun 2

我曾经必须弄清楚一个字符串是否包含 Java 方法调用(包括包含非 ASCII 字符的方法名称)。

以下内容对我来说效果很好,尽管它也找到了构造函数调用。希望能帮助到你。

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)