我尝试利用匹配器功能“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/