4

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()

4

2 に答える 2

4

への呼び出しは、.lookingAt()一致して消費する T234ため、次の呼び出しは一致しない -.find()で始まります。bird

最初からやり直すには、マッチャー オブジェクトをリセットする必要があります。

または、正規表現で文字列の開始アンカーを使用して、.find()すぐに使用します。

Matcher matches = Pattern.compile("^T\\d+").matcher("T234bird");
if (matches.find())
    System.out.println(matches.group());
于 2012-09-27T15:49:25.813 に答える
3

試行 1 では、呼び出しがlookingAt一致T234し、次の への呼び出しは、前の一致の最後でfind一致の検索を開始します。文字列の先頭に戻りたい場合は、 を呼び出す必要があります。これは、Matcher.find()のドキュメントで説明されています。Matcher.reset()

このメソッドは、このマッチャーの領域の先頭から開始します。または、メソッドの以前の呼び出しが成功し、その後マッチャーがリセットされていない場合は、以前の一致で一致しなかった最初の文字から開始します。

、、および同じ方法でlookingAt機能することに注意してください。したがって、文字列の先頭のみに関心がある場合は、これを実行できます。startendgroupfind

Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
if (matches.lookingAt())
    System.out.println(matches.group());

前の一致の終わりではなく、常に文字列の先頭から検索を開始するため、if代わりにwhileここを使用する必要があります。そのため、永久にループします。lookingAtwhile

于 2012-09-27T15:51:33.483 に答える