Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/382.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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,考虑3个用于从字符串中删除非拉丁字符的正则表达式 String x = "some†¥¥¶¶ˆ˚˚word"; long now = System.nanoTime(); System.out.println(x.replaceAll("[^a-zA-Z]", "")); // 5ms System.out.println(System.nanoTime() - now); now = System.nanoTime(); System

考虑3个用于从字符串中删除非拉丁字符的正则表达式

    String x = "some†¥¥¶¶ˆ˚˚word";

    long now = System.nanoTime();
    System.out.println(x.replaceAll("[^a-zA-Z]", ""));     // 5ms
    System.out.println(System.nanoTime() - now);

    now = System.nanoTime();
    System.out.println(x.replaceAll("[^a-zA-Z]+", ""));    // 2ms
    System.out.println(System.nanoTime() - now);

    now = System.nanoTime();
    System.out.println(x.replaceAll("[^a-zA-Z]*", ""));    // <1ms
    System.out.println(System.nanoTime() - now);
String x=“一些†¥¥¨ˆ˚单词”;
long now=System.nanoTime();
System.out.println(x.replaceAll(“[^a-zA-Z],”);//5ms
System.out.println(System.nanoTime()-now);
now=System.nanoTime();
System.out.println(x.replaceAll(“[^a-zA-Z]+”,”);//2ms
System.out.println(System.nanoTime()-now);
now=System.nanoTime();

System.out.println(x.replaceAll(“[^a-zA-Z]*”,”);// 第一个比较慢,因为正则表达式分别匹配每个非拉丁字符,所以
replaceAll
分别对每个字符进行操作


其他模式匹配整个非拉丁字符序列,因此
replaceAll
可以一次性替换整个序列。不过,我无法解释这两者之间的性能差异。可能与正则表达式引擎中处理
*
+
的不同有关。

最后一个将用空字符串替换空字符串(除非进行优化,我不知道编译器),这似乎有点不必要…;-)


如果非拉丁字符是邻接的,第一个将比第二个搜索更多次。否则就不行了。因此,我猜在某些文本中,1和2的时间可能大致相同,而在其他文本中,1的时间可能更长。

正如@Andrew Cooper所说,*和+之间的区别在于+必须向前看一点,以确保模式不会出现多次,所以速度会慢一点