I want to find any method call in given code. I am splitting code with semicolon as delimiter. In the end I am interested in finding names of methods which have been called in given code.
I need a regular expression to match the method call pattern.
The Match(String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.
The re.search() function will search the regular expression pattern and return the first occurrence. Unlike Python re. match(), it will check all lines of the input string. If the pattern is found, the match object will be returned, otherwise “null” is returned.
In C#, Regular Expression is a pattern which is used to parse and check whether the given input text is matching with the given pattern or not. In C#, Regular Expressions are generally termed as C# Regex. The . Net Framework provides a regular expression engine that allows the pattern matching.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With