Java - 模式匹配奇怪的行为

标签 java regex

我必须执行部分模式匹配,因此我针对以下输入测试了模式匹配

Pattern p = Pattern.compile("hello");
Matcher m = p.matcher("[a-z]");

谁能解释一下为什么

System.out.println(m.find() || m.hitEnd());

打印 true while

System.out.println(m.hitEnd());

打印false

最佳答案

看看这个程序:

Pattern p = Pattern.compile("hello");
Matcher m = p.matcher("[a-z]");
System.out.println(m.hitEnd()); // prints false
System.out.println(m.find());  // prints false
System.out.println(m.hitEnd()); // prints true

注意,第一次调用 m.hitEnd() 返回 false。看JavaDoc ,它说:

Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.

这里返回false,因为它是在调用m.find()之前调用的,所以匹配器还没有执行任何匹配操作。调用 m.find() 后,它返回 true (因为 find() 消耗完整的输入字符串并命中结束)。 JavaDoc 中也解释了其含义:

When this method returns true, then it is possible that more input would have changed the result of the last search.

当返回 true 时,意味着匹配器到达了输入的末尾。在这种情况下,命中意味着达到,而不是匹配。 (输入完全被匹配器消耗)。

编辑

我希望您想要的是,[a-z] 是正则表达式 hello 的输入字符串,而不是相反。如果你有

Pattern p = Pattern.compile("[a-z]"); // The regex needs to be compiled.
Matcher m = p.matcher("hello");       // The input is given to the matcher
while (m.find()) {                    // In this case, returns true 5 times
    System.out.println(m.group() + ", ");
}

你的输出将是

h, e, l, l, o, 

关于Java - 模式匹配奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14441070/

相关文章:

java - 递归函数StackOverflowError

Java 竞赛小程序不工作

java - 什么是 Java 中的 IncompatibleClassChangeError 异常?

javascript - 使用javascript从url中提取数字?

正则表达式 来自 MS Outlook 主题行的 5 位数字

java - TextWatcher 在启动后关闭我的应用程序

java - 在 JPanel 上绘制椭圆时遇到问题

c# - 如何验证 DropDownList 中的选定值?

用于匹配示例代码后的字符串的正则表达式

python - 正则表达式匹配除引号之间的所有单词