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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2469244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:06:35  来源:igfitidea点击:

What's the difference between String.matches and Matcher.matches?

java

提问by Winston Chen

What's the difference between String.matches and Matcher.matches? Is there any difference in terms of performance or other things?

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

采纳答案by Kilian Foth

Absolutely. A Matcheris created on on a precompiled regexp, while String.matchesmust recompile the regexp every time it executes, so it becomes more wasteful the more often you run that line of code.

绝对地。AMatcher是在预编译的正则表达式上创建的,而String.matches每次执行时都必须重新编译正则表达式,因此运行该行代码的次数越多,浪费就越大。

回答by chburd

String.matchesinternally calls Pattern.matches(regex, str). The problem with it is that each time you call it you recompile the pattern, which cost some resources.

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

It is better to compile your pattern once, then try to match it against all the Strings you want. I personally use a Patterns class containing all my pattern in my app declared as final and static

最好编译一次您的模式,然后尝试将它与您想要的所有字符串进行匹配。我个人使用一个 Patterns 类,其中包含我的应用程序中声明为 final 和 static 的所有模式

回答by saugata

String.matches internally delegates to Matcher.matches.

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

If you are reusing the Pattern object then there will be some performance benefit. Also when using Pattern/Matcher you can groupyour regular expressions and get the matching parts.

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

The bottomline is if you have a regex that you will use only once and you don't need to parse your string to get matching parts then use either. But if you are going to use the same regex against multiple strings or you need parts of the String based on regex create a Pattern and get Matcher using it.

底线是,如果您有一个只使用一次的正则表达式,并且您不需要解析您的字符串来获取匹配的部分,然后使用。但是,如果您要对多个字符串使用相同的正则表达式,或者您需要基于正则表达式的字符串的一部分,请创建一个 Pattern 并让 Matcher 使用它。

回答by Rajind Ruparathna

Out of curiosity I did this small test on the time differences. Turns out that using a pre-compiled pattern is more than 5 times fasterthan using String.matches method.

出于好奇,我对时差做了这个小测试。事实证明,使用预编译模式比使用 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);
    }
}

Output (nanoseconds):

输出(纳秒):

Duration pre compiled: 4505.0

In place compiled:    44960.0

P.S. This test is a quick and dirty test and may not be according to performance benchmarking practises. If you want to get highly accurate results please use a micro benchmarking tool.

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

回答by Karishma Verma

Pattern.compile compiles the pattern so that when you execute metcher.matches, pattern is not re compiled again and again. Pattern.compile pre compiles it. However, if you use string.matches, it compiles the pattern everytime you execute this line. So, it is better to use Pattern.compile.

Pattern.compile 编译模式,这样当你执行 metcher.matches 时,模式不会一次又一次地重新编译。Pattern.compile 预编译它。但是,如果您使用 string.matches,它会在您每次执行此行时编译模式。所以,最好使用Pattern.compile。