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 = " 

我希望它打印:

 "Match = " 

我需要在模式中做些什么改变?

使用*?让你的* 非贪婪 / 不情愿 *?

 Pattern ptrn = Pattern.compile("\\b(A.*?B)\\b"); 

默认情况下,模式将表现得很贪婪,并且匹配尽可能多的字符以满足模式,即直到最后一个B。

请参阅文档和本教程中的 Reluctant Quantifiers

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

 Pattern ptrn = Pattern.compile("\\b(A.*?B)\\b"); 

*是贪婪量词,匹配尽可能多的字符以满足模式。 直到示例中的最后一次B出现。 这就是为什么你需要使用不情愿的一个: *? ,这将尽可能少的字符。 所以,你的模式应该稍微改变一下:

 Pattern ptrn = Pattern.compile("\\b(A.*?B)\\b"); 

请参阅文档和本教程中的 “不情愿的量词”。

也许比制造*不情愿/懒惰更明确的是说你正在寻找A,然后是一堆不是B的东西,接着是B:

 Pattern ptrn = Pattern.compile("\\b(A[^B]*B)\\b");