Matcher.lookingAt()
呼び出しが に影響することに気付きましたMatcher.find()
。lookingAt()
コードを実行したところ、 trueが返されました。その後find()
、一致を返すように実行したところ、falseになりました。lookingAt()
呼び出しを削除すると、 truefind()
が返され、一致が出力されます。誰かが理由を知っていますか?
トライアル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()
。