[英]Why does Matcher.find() return false when run after Matcher.lookingAt()?
我注意到调用Matcher.lookingAt()
会影响Matcher.find()
。 我在我的代码中运行了lookingAt()
,它返回true 。 当我然后运行find()
以便我可以开始返回匹配时,我得到了错误 。 如果我删除了lookingAt()
调用, find()
返回true并打印我的匹配项。 有谁知道为什么?
Trial1:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
System.out.println(matches.lookingAt()); //after running this, find() will return false
while (matches.find())
System.out.println(matches.group());
//Output: true
Trial2:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
//System.out.println(matches.lookingAt()); //without this, find() will return true
while (matches.find())
System.out.println(matches.group());
//Output: T234
Trial3:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
while (matches.lookingAt())
System.out.println(matches.group());
//Output: T234 T234 T234 T234 ... till crash
//I understand why this happens. It's not my question but I just included it in case someone may try to suggest it
最终,我想要实现的是:首先确认匹配位于字符串的开头,然后打印出来。 我最终做了:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
if(matches.lookingAt())
System.out.println(matches.group());
//Output: T234
这解决了我的问题,但我的问题是:有谁知道为什么lookingAt()
会影响find()
?
对.lookingAt()
的调用匹配并消耗 T234
,因此以下.find()
调用从bird
开始 - 不匹配。
您需要重置匹配器对象才能从头开始。
或者只是在你的正则表达式中使用一个字符串起始锚点并立即使用.find()
:
Matcher matches = Pattern.compile("^T\\d+").matcher("T234bird");
if (matches.find())
System.out.println(matches.group());
在审判1,呼叫lookingAt
匹配T234
,和你的后续调用find
开始寻找比赛在前面的比赛结束 。 如果你想回到字符串的开头,你需要调用Matcher.reset()
。 这在Matcher.find()的文档中有解释:
此方法从此匹配器区域的开头开始,或者,如果方法的先前调用成功并且匹配器尚未重置,则在第一个与上一个匹配不匹配的字符处开始。
请注意, lookingAt
与start
, end
和group
的工作方式与find
相同,因此如果您只对字符串的开头感兴趣,则可以执行此操作:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
if (matches.lookingAt())
System.out.println(matches.group());
你必须使用if
代替while
在这里,因为lookingAt
总是开始盯着字符串的开头,而不是在以前的比赛结束,所以while
只是循环永远。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.