dmz73
dmz73

Reputation: 1608

Java regex to match first argument of a method call in Java code

Given the following text

log.debug("find by example successful, result size: " + results.size(), exception);

How can I match the first argument of the method call, in this case the text between the first parenthesis and the last comma:

"find by example successful, result size: " + results.size()

I started with the following pattern:

Pattern.compile("log\\.([\\w]+)\\((.+?)\\)", Pattern.DOTALL);

but if I try to match up to the comma it won't work:

Pattern.compile("log\\.([\\w]+)\\((.+?),?\\)", Pattern.DOTALL);

Upvotes: 0

Views: 182

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

You need to include the , in the regex and also you need to remove the ? quantifier inside the second capturing group. So that the regex engine would match all the characters upto the last , greedily.

Pattern.compile("log\\.(\\w+)\\((.+),", Pattern.DOTALL);

And get the string you want from group index 2.

String s = "log.debug(\"find by example successful, result size: \" + results.size(), exception);";
Pattern regex = Pattern.compile("log\\.(\\w+)\\((.+),");
 Matcher matcher = regex.matcher(s);
 while(matcher.find()){
        System.out.println(matcher.group(2));
}

Output:

"find by example successful, result size: " + results.size()

Upvotes: 1

vks
vks

Reputation: 67968

\\(.*,

Try this.See demo .This will give the match between first ( and last ,.

https://regex101.com/r/nL5yL3/10

Upvotes: 0

Related Questions