String.matches和Matcher.matches有什么区别?

Win*_*hen 44 java

String.matches和Matcher.matches有什么区别?在表现或其他方面有什么不同吗?

Kil*_*oth 54

绝对.A Matcher是在预编译的regexp上创建的,而String.matches每次执行时都必须重新编译regexp,因此运行该代码行的频率越高,就越浪费.


sau*_*ata 29

String.matches在内部委托给Matcher.matches.

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();
}
Run Code Online (Sandbox Code Playgroud)

如果您正在重用Pattern对象,那么将会有一些性能优势.此外,使用Pattern/Matcher时,您可以对正则表达式进行分组并获取匹配的部分.

最重要的是,如果你有一个正则表达式,你将只使用一次,你不需要解析你的字符串来获得匹配的部分,然后使用其中任何一个.但是如果你打算对多个字符串使用相同的正则表达式,或者你需要基于正则表达式的部分字符串创建一个模式并使用它来获取匹配器.


Raj*_*hna 11

出于好奇,我对时间差异进行了这个小测试.事实证明,使用预编译模式比使用String.matches方法快5倍以上.

import java.util.regex.Pattern;

/**
 * @author Rajind Ruparathna
 */
public class MatchesTest {
    public static void main(String Args[]) {
        String first = "@\\{message.headers\\.?([^\\}]*)\\}";
        String second = "@\\{message.headers.wolla\\}";
        long start, end, total;
        float avg;
        int NUM_OF_ITERATIONS = 100;

        Pattern pattern = Pattern.compile(first);

        total = 0;
        start = 0;
        end = 0;
        avg = 0;

        for (int i=0; i< NUM_OF_ITERATIONS; i++) {
            start = System.nanoTime();
            pattern.matcher(second).matches();
            end = System.nanoTime();
            total = total + (end - start);
        }
        avg = total/NUM_OF_ITERATIONS;
        System.out.println("Duration pre compiled: " + avg);

        total = 0;
        start = 0;
        end = 0;
        avg = 0;

        for (int i=0; i< NUM_OF_ITERATIONS; i++) {
            start = System.nanoTime();
            first.matches(second);
            end = System.nanoTime();
            total = total + (end - start);
        }
        avg = total/NUM_OF_ITERATIONS;
        System.out.println("In place compiled: " + avg);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出(纳秒):

Duration pre compiled: 4505.0

In place compiled:    44960.0
Run Code Online (Sandbox Code Playgroud)

PS此测试是一项快速而肮脏的测试,可能不符合性能基准测试实践.如果您想获得高度准确的结果,请使用微型基准测试工具.


chb*_*urd 5

String.matches内部呼叫Pattern.matches(regex, str).它的问题在于,每次调用它时都会重新编译模式,这会花费一些资源.

最好先编译一次模式,然后尝试将它与所需的所有字符串进行匹配.我个人使用一个Patterns类,其中包含我的app中声明为final和static的所有模式

  • "我个人使用一个Patterns类,其中包含我的app中声明为final和static的所有模式." 最好将模式放在实际使用它们的类或方法中.这样,一起更改的代码就打包在一起了.参见[Common Closure Principle](http://c2.com/cgi.com/ciki/wiki?CommonClosurePrinciple). (2认同)
  • 我确实同意你的观点.我的意见在4年内发生了变化:-) (2认同)