Java Regex模式匹配在任何字符序列之后首次出现“边界” [英] Java Regex pattern matching first occurrence of “boundary” after any character sequence

查看:96
本文介绍了Java Regex模式匹配在任何字符序列之后首次出现“边界”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to set a pattern which will find a capture group limited by the first occurrence of the "boundary". But now the last boundary is used.

例如:

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

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

What do I need to change within the pattern?

推荐答案

使用 * 非贪婪 / 不情愿使用 *?

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

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

By default, the pattern will behave greedily, and match as many characters as possible to satisfy the pattern, that is, up until the last B.

不情愿的量词 /docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html\"rel =noreferrer>文档,以及本教程

See Reluctant Quantifiers from the docs, and this tutorial.

这篇关于Java Regex模式匹配在任何字符序列之后首次出现“边界”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆