【发布时间】:2012-09-27 23:58:24
【问题描述】:
我注意到调用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()?
【问题讨论】: