Java Regex模式匹配任何字符序列后首次出现的"边界"

amp*_*ent 15 java regex

我想设置一个模式,它将找到一个受第一次出现的"边界"限制的捕获组.但现在使用了最后一个边界.

例如:

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)

默认情况下,该模式将表现得贪婪,并匹配尽可能多的字符可能满足的模式,也就是说,直到最后.

不愿量词该文档,和本教程.


Rei*_*eus 5

不要使用贪婪表达式进行匹配,即:

Pattern ptrn = Pattern.compile("\\b(A.*?B)\\b");
Run Code Online (Sandbox Code Playgroud)