2016-05-11 3 views
2

賢明な優れたパフォーマンスとは何ですか:
string.matches("regex")
または
Pattern.compile("regex").matches(string).find() は? String.matches(String regex)Pattern.javaPattern.matches( "正規表現")

+1

回答から:それは依存しています。 – Tom

+1

リンゴ対オレンジのパフォーマンスを比較できません。 'matches()'と 'find()'は同じ動作ではありません。 ---また、 'matches()'ではなく 'compile()'と 'find()'の間に 'matcher()'を置かなければならないので、コードはコンパイルされません。 – Andreas

答えて

4

実装にString.javamatches()、またはAPIを介してマッチングされた私は何を参照しています

Pattern.matches(String regex, CharSequence input)

public boolean matches(String regex) { 
    return Pattern.matches(regex, this); 
} 

は、インプリメンテーション:

public static boolean matches(String regex, CharSequence input) { 
    Pattern p = Pattern.compile(regex); 
    Matcher m = p.matcher(input); 
    return m.matches(); 
} 

結論:str.matches(regex) i と全く同じPattern.compile(regex).matcher(str).matches()とします。

注:matches()と同じですが、find()と同じではありません。あなたはMatcherにアクセスする必要が

  • Pattern.compile()を使用して

    があれば必要な/良いです。
    など。キャプチャグループの結果が必要です。

  • 同じmatches(regex)を何度も呼び出します。
    regexパターンをコンパイルするだけで、パフォーマンスが向上します。

0

正規表現を再利用するかどうかによって異なります。もしそうなら、一度だけコンパイルするほうがいいです。 Stringmatches機能はPattern.matchesで定義されています

public boolean matches(String regex) { 
    return Pattern.matches(regex, this); 
} 

スニペットopenJDK7