Regex for finding method calls

I want to find any method call in the given code. Therefore, I separate the code with a semicolon as a separator. Therefore, in the end, I am interested in finding the names of the methods that were called in the given code. I need a regular expression to match the method call pattern. Please, help!

+6
source share
3 answers

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

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

If there are unqualified calls {i.e. calls in this form: methodName (..)}, I used:

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

Although it will also find constructors.

+1
source

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

It worked pretty well for me, although it also finds constructor calls. Hope this helps.

 /** * Matches strings like {@code obj.myMethod(params)} and * {@code if (something)} Remembers what in front of the parentheses and * what 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; } 
0
source
 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)); } } 
0
source

Source: https://habr.com/ru/post/909132/


All Articles