我想设置一个模式,它将找到一个受第一次出现的"边界"限制的捕获组.但现在使用了最后一个边界.
例如:
String text = "this should match from A to the first B and not 2nd B, got that?";
Pattern ptrn = Pattern.compile("\\b(A.*B)\\b");
Matcher mtchr = ptrn.matcher(text);
while(mtchr.find()) {
String match = mtchr.group();
System.out.println("Match = <" + match + ">");
}
Run Code Online (Sandbox Code Playgroud)
打印:
"Match = <A to the first B and not 2nd B>"
Run Code Online (Sandbox Code Playgroud)
我希望它打印:
"Match = <A to the first B>"
Run Code Online (Sandbox Code Playgroud)
在模式中需要更改什么?
pb2*_*b2q 43
让你的*
非贪婪/勉强使用*?
:
Pattern ptrn = Pattern.compile("\\b(A.*?B)\\b");
Run Code Online (Sandbox Code Playgroud)
默认情况下,该模式将表现得贪婪,并匹配尽可能多的字符可能满足的模式,也就是说,直到最后乙.
不要使用贪婪表达式进行匹配,即:
Pattern ptrn = Pattern.compile("\\b(A.*?B)\\b");
Run Code Online (Sandbox Code Playgroud)