给定以下文本
log.debug("find by example successful, result size: " + results.size(), exception);
如何匹配方法调用的第一个参数,在本例中为第一个括号和最后一个逗号之间的文本:
"find by example successful, result size: " + results.size()
我从以下模式开始:
Pattern.compile("log\\.([\\w]+)\\((.+?)\\)", Pattern.DOTALL);
但是如果我尝试匹配逗号,它将不起作用:
Pattern.compile("log\\.([\\w]+)\\((.+?),?\\)", Pattern.DOTALL);
最佳答案
您需要在正则表达式中包含 ,
,还需要删除第二个捕获组内的 ?
量词。这样正则表达式引擎就会贪婪地匹配直到最后一个 ,
的所有字符。
Pattern.compile("log\\.(\\w+)\\((.+),", Pattern.DOTALL);
并从组索引 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));
}
输出:
"find by example successful, result size: " + results.size()
关于Java 正则表达式匹配 Java 代码中方法调用的第一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27397095/