我注意到调用 Matcher.lookingAt()
会影响 Matcher.find()
。我在我的代码中运行了 lookingAt()
,它返回了 true。然后,当我运行 find()
以便开始返回匹配项时,我得到了 false。如果我删除 lookingAt()
调用,find()
返回 true 并打印我的匹配项。有谁知道为什么?
试验1:
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
试验 2:
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
试验 3:
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()
?
最佳答案
在试验 1 中,调用 lookingAt
匹配 T234
,随后调用 find
开始在 处寻找匹配项上一场比赛结束。如果你想回到字符串的开头,你需要调用 Matcher.reset()
. Matcher.find() 的文档中对此进行了解释:
This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.
请注意,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
会一直循环下去。
关于java - 为什么 Matcher.find() 在 Matcher.lookingAt() 之后运行时返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12625171/