java - 大型列表的正则表达式优化

标签 java regex optimization

我正在比较两个字符串列表以找到可能的匹配项。示例:

public class Tester {

    public static void main(String[] args) {

        List<String> test = new ArrayList<String>();
        List<String> test2 = new ArrayList<String>();

        test.add("3H0875AAAA0012");
        test.add("3H0875AABB0018");
        test.add("3H0875AAAC0010");
        test2.add("3H0875AA");


        for(String s2: test2){
            for (String s: test){
                if (s.matches(".*" + s2 + ".*")){
                    System.out.println("Match");
                }
            }
        }
    }
}

基本上对于 test2 中的每个字符串,我想看看 test 中是否有任何字符串完全或部分包含 test2。上面代码的输出应该是:

Match 
Match 
Match

但是,在我的真实案例场景中,我在测试中有大约 225K 个字符串,在 test2 中有大约 5K 个字符串。这个比较过程花费的时间太长,想看看是否可以优化比较。分析 test2 中的前 1.5K 项大约需要 10 分钟。因此完成比较至少需要 30 到 40 分钟。

提前致谢

最佳答案

我认为你不应该为此使用 regex:我相信查看 String#contains(这里是 link to its javadoc entry)会给你更好的结果, 在性能方面 ;)

例如,您的代码可以是:

for(final String s2: test2){
    for (final String s: test){
        if(s.contains(s2)) {
            System.out.println("Match");
        }
    }
}

关于java - 大型列表的正则表达式优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22951558/

相关文章:

javascript - JavaScript 中的正则表达式怪异

javascript - 组合正则表达式而不用 Javascript 填充结果

python - 我的 Django 查询 : how to improve the speed of list view

php - xdebug,分析器输出有问题

java - JOOQ 按问题排序

java - Spring 尝试将 URL 的最后部分解析为 Long 参数

java - 如何以 YYYYMMDD 格式提取星期一或星期四的数据?

java - 重复选择或使用 IN 子句,哪个更快?

Python - 提取正则表达式匹配并一次性替换它?

MySQL 多查询限制为 1,UNION 会提高速度吗?