我想在给定的代码中找到任何方法调用。所以我用分号作为分隔符拆分代码。所以最后我有兴趣找到在给定代码中调用的方法的名称。我需要一个正则表达式来匹配方法调用模式。请帮忙!!
答案 0 :(得分:1)
对于合格的电话{即,以这种形式的电话:[objectName | className] .methodName(..)},我一直在使用:
(\.[\s\n\r]*[\w]+)[\s\n\r]*(?=\(.*\))
当存在不合格的电话时(即,以这种形式发出的电话:methodName(..)},我一直在使用:
(?!\bif\b|\bfor\b|\bwhile\b|\bswitch\b|\btry\b|\bcatch\b)(\b[\w]+\b)[\s\n\r]*(?=\(.*\))
虽然,这也会找到构造函数。
答案 1 :(得分:0)
我曾经不得不弄清楚一个字符串是否包含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;
}
答案 2 :(得分:0)
File f=new File("Sample.java"); //Open a file
String s;
FileReader reader=new FileReader(f);
BufferedReader br=new BufferedReader(reader); //Read file
while((s=br.readLine())!=null){
String regex="\\s(\\w+)*\\(((\\w+)*?(,)?(\\w+)*?)*?\\)[^\\{]";
Pattern funcPattern = Pattern.compile(regex);
Matcher m = funcPattern.matcher(s); //Matcher is used to match pattern with string
if(m.find()){
System.out.printf(group(0));
}
}
答案 3 :(得分:0)
我认为这可以工作,但与参数的辅助正则表达式不匹配:
String regex = "\\s*(\\w+?)\\s*\\(((\\w+?)\\s*,?\\s*)*\\)\\s*";