Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 组合两个正则表达式的时间复杂度是多少?_Java_Regex - Fatal编程技术网

Java 组合两个正则表达式的时间复杂度是多少?

Java 组合两个正则表达式的时间复杂度是多少?,java,regex,Java,Regex,假设我有一个正则表达式列表,希望输入字符串与之匹配,如: List<String> regexList = new ArrayList<>(); regexList.add("(.*)apple"); // regex1 - anything ending with apple regexList.add("smart(.*)"); // regex2 - anything starting with smart boolean isMatching(input) {

假设我有一个正则表达式列表,希望输入字符串与之匹配,如:

List<String> regexList = new ArrayList<>();
regexList.add("(.*)apple"); // regex1 - anything ending with apple
regexList.add("smart(.*)"); // regex2 - anything starting with smart

boolean isMatching(input) {
    for (String regex : regexList) {
        if (input.matches(regex)) return true;
    }
    return false;
}
现在假设有N个正则表达式来处理。 两种方法的时间复杂度是多少?

两种方法的复杂度都是
O(N*W*k)
,其中:

  • N
    是正则表达式的数目
  • W
    是所有正则表达式中复杂度最大的一个(在Java中,正则表达式的指数复杂度最高,)
  • k
    是正在测试的字符串数

不同方法的运行时间可能不同。或者,如果Java正则表达式引擎以一种有意义的方式对这种情况进行优化,那么将正则表达式组合在一起将具有更好的性能。如果性能至关重要,请参阅以获取另一个想法。

您是否运行了代码并进行了一些基准测试?我想
startsWith
endsWith
的循环速度要快得多。如果没有进行任何测量,我想组合的regexp初始化匹配器需要更长的时间,但实际的匹配速度要比使用循环快得多。实际上,整体速度的提高还取决于输入的长度。每次调用
.matches()
,都必须编译正则表达式,因为您使用的是字符串而不是只编译一次的。然而,这只有在你想让它更快的时候才有意义,而不仅仅是好奇时间的复杂性。
String regexCombined = "((.*)apple)|(smart(.*))";

boolean isMatching(input) {
    return input.matches(regexCombined);
}