java - java.util.regex.Matcher::useAnchoringBounds 如何工作?

标签 java regex

我尝试利用匹配器功能“useAnchoringBounds”。但我看不到将其从默认值“true”设置为“false”有任何效果。

Matcher 方法“useAnchoringBounds”的 Javadoc 说:

[…] Without anchoring bounds, the boundaries of this matcher's region will not match anchors such as ^ and $. […]

Matcher matcher = Pattern.compile("^a$").matcher("a");
matcher.useAnchoringBounds(false);
System.out.println(matcher.find() + " " + matcher.group());// true a

Matcher matcher = Pattern.compile("^a$").matcher("ab");
matcher.useAnchoringBounds(false);
System.out.println(matcher.find());// false

在这两个示例中,设置“useAnchoringBounds”不会影响匹配结果。 “useAnchoringBounds”设置如何影响匹配?

解释示例

Matcher anchoringBounds = Pattern.compile("^a$").matcher("xax");
    anchoringBounds.region(1, 2);// sub region is: "a"
    assert anchoringBounds.find();// sub region is treated like a complete input by default
    anchoringBounds.useAnchoringBounds(false);// Now treat the region as incomplete part of the whole input
    assert !anchoringBounds.find();// "a" is no longer considered at the beginning of line ^

最佳答案

该方法定义中的关键词是“region”。

该区域是完整字符串的一部分,您可以定义它。例如:

Matcher matcher = Pattern.compile("^a$").matcher("xxxayyy");
matcher.region(3, 4);
matcher.useAnchoringBounds(false);
System.out.println("find=" + matcher.find());

在本例中,我们将区域定义为“xxxayyy”内的“a”。现在,匹配器是否应该将该区域的边界视为锚定边界?

在默认的true中,这与将匹配器的字符串设置为“a”相同,并且模式将被匹配。

但是当您设置为 false 时,它与锚定的 a 不匹配。它考虑整个字符串上下文中的区域。

关于java - java.util.regex.Matcher::useAnchoringBounds 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61184240/

相关文章:

java - 创建向导 Swing

javascript - 不得在字符范围内使用 Intellij IDEA 正则表达式字符类

javascript - 正则表达式匹配!

regex - R - 提取所有匹配模式的字符串并创建关系表

regex - Bash 复制所有内容与模式匹配的目录

java - 无法找到命名参数

java - 如何使用用户创建的对象的变量?(Java)

java - Google App Engine Ant 宏 - 本地还是生产?

java - 点击主页按钮时 libGDX 纹理消失

java - 笑脸的正则表达式模式无法区分负号和范围