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
Java 模式搜索性能差_Java_Performance_Pattern Matching - Fatal编程技术网

Java 模式搜索性能差

Java 模式搜索性能差,java,performance,pattern-matching,Java,Performance,Pattern Matching,我使用一个正则表达式来搜索一个非常特定的模式,它对应的目录大小只有大约106MB。大约需要10秒钟才能完成 我能做些什么来提高性能吗 package com.JFileReader; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.r

我使用一个正则表达式来搜索一个非常特定的模式,它对应的目录大小只有大约106MB。大约需要10秒钟才能完成

我能做些什么来提高性能吗

package com.JFileReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileData {

    public static void main(String[] args) {
        File dir = new File("/Users/me/Desktop/");

        if(dir.isFile()) { handleFile(dir); }
        if(dir.isDirectory()) { handleDir(dir); }
    }

    public static void handleFile(File aFile) {
        String regex = "[a-zA-Z]+[.][a-zA-Z]+[@][a-zA-Z]+[.][a-zA-Z]+";
        Pattern pattern = Pattern.compile(regex);

        try {
            BufferedReader br = new BufferedReader(new FileReader(aFile));
            Matcher m; 

            String line;
            while ((line = br.readLine()) != null) {
                m = pattern.matcher(line);
                if (m.find()) {
                    System.out.println("Found: " + aFile);
                }
            }
            br.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public static void handleDir(File dir) {
        for (File file : dir.listFiles()) {
            if(file.isFile()) { handleFile(file); }
            if(file.isDirectory()) { handleDir(file); }
        }
    }
}

重复编译regex模式(针对每个文件)是一种相对昂贵的浪费


您可以定义一次,然后继续使用同一个实例。

重复编译regex模式(针对每个文件)是一种相对昂贵的浪费


您可以定义一次,然后继续使用相同的实例。

您可以使用所有格量词:

String regex = "[a-zA-Z]++\\.[a-zA-Z]++@[a-zA-Z]++\\.[a-zA-Z]++";

当你使用所有格量词时,正则表达式引擎不会记录回溯位置,也不会在匹配失败时返回尝试其他可能性

你可以使用所有格量词:

String regex = "[a-zA-Z]++\\.[a-zA-Z]++@[a-zA-Z]++\\.[a-zA-Z]++";

当你使用所有格量词时,正则表达式引擎不会记录回溯位置,也不会在匹配失败时返回尝试其他可能性