我注意到调用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()
?