java - 关于 requireEnd Matcher 方法的澄清

标签 java regex methods

直接来自this java API:

public boolean requireEnd()

Returns true if more input could change a positive match into a negative one.

If this method returns true, and a match was found, then more input could cause the match to be lost. If this method returns false and a match was found, then more input might change the match but the match won't be lost. If a match was not found, then requireEnd has no meaning.

Returns: true iff more input could change a positive match into a negative one.

我在网上找不到任何具体的例子。

有人可以向我展示它的使用示例吗? 提前致谢。

最佳答案

让我们举一个简单的例子:

public static void main(final String... args)
{
    final Pattern p = Pattern.compile("cat$");

    final Matcher m = p.matcher("I have a cat");
    m.find(); // finds a match
    System.out.println(m.requireEnd()); // prints true
}

正则表达式末尾有一个 anchor ;文档称,如果提供更多输入,“[...]可能会导致匹配失败”。的确。考虑这个输入:

"I have a catflap"

正则表达式不再匹配:匹配失败。

如果现在我们将 "cat$" 替换为 "cat" 那么 .requireEnd() 将返回 false:使用上面的输入,cat 仍会被正则表达式引擎匹配。

关于java - 关于 requireEnd Matcher 方法的澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17618812/

相关文章:

java - 类设计查询

java - 创建通用类列表

java - 当起始节点不存在时,Talend Neo4j 关系组件会抛出错误

c - C中的Posix正则表达式匹配...全匹配异常?

javascript - 如何在javascript中使用正则表达式从字符串中提取日期值?

java - Rational 类中相互调用方法

java - 什么时候创建 Enum 实例?

java - RegEX:如何匹配未包围的字符串

c# - 如何强制继承类在 C# 中实现静态方法?

methods - 方法调用语法 `foo.method()`和UFCS `Foo::method(&foo)`有什么区别?