2

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

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

谁能解释我为什么

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

打印true

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

打印false

4

3 回答 3

2

更新:

因为m.find()它自己完全处理了模式,但没有找到匹配项(并返回false)。该模式在此调用后被完全使用,因此hitEnd()将 result true

在第二次调用中,模式没有被消耗,所以hitEnd()返回false

对于hitEnd()Javadoc 说:

如果在此匹配器执行的最后一次匹配操作中搜索引擎命中输入结尾,则返回 true。

反思@jlordo 的评论:也许您想更改模式和文本

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

因为"[a-z]"它看起来像一个模式。

于 2013-01-21T14:49:32.980 回答
2

看看这个程序:

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,它说:

如果在此 matcher 执行的最后一次匹配操作中搜索引擎命中了输入的结尾,则返回 true 。

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

当此方法返回 true 时,更多输入可能会改变上次搜索的结果。

当它返回 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, 
于 2013-01-21T15:06:28.597 回答
0
System.out.println(m.find() || m.hitEnd());

m.find() 返回一个布尔值 - 该布尔值是假的。我们刚刚处理了输入搜索的结尾——这使得 m.hitend() 结果为真。假 || 因此,true 等于 true。

前面的操作结束了——如果..好吧,hitend() 返回 true,这里是 javadoc:

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

我们没有到达终点……在最后一次手术中。所以 hitend() 是假的。连续调用将导致错误。

于 2013-01-21T14:50:05.283 回答