gpt4 book ai didi

Java 正则表达式模式匹配任何字符序列后第一次出现的 “boundary”

转载 作者:太空狗 更新时间:2023-10-29 22:59:13 25 4
gpt4 key购买 nike

我想设置一个模式,该模式将找到一个受第一次出现的“边界”限制的捕获组。但是现在使用最后一个边界。

例如:

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 = <A to the first B and not 2nd B>"

我希望它打印:

"Match = <A to the first B>"

我需要在模式中更改什么?

最佳答案

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

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

默认情况下,模式会贪婪地匹配尽可能多的字符以满足模式,即直到最后一个B

参见 the docs 中的 Reluctant Quantifiers , 和 this tutorial .

关于Java 正则表达式模式匹配任何字符序列后第一次出现的 “boundary”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12848600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com