【发布时间】:2020-04-02 11:16:16
【问题描述】:
我正在尝试匹配多行文本上的大正则表达式。一些正则表达式的执行时间大约需要 3-4 分钟。这基本上是导致性能问题 代码sn-p
boolean matchedRegex = false;
for (Rules rule : rules) {
String mergedRegex = rule.getRegexes().stream().collect(Collectors.joining("|"));
final Pattern pattern = Pattern.compile(mergedRegex, Pattern.MULTILINE | Pattern.DOTALL);
System.out.println(String.format("Pattern: %s", pattern));
if (pattern.matcher(text).find()) {
matchedRegex = true;
break;
}
}
mergedRegex = "(?=.*MORTGAGE\b)(?=.* This Security Instrument is given to\b).*|(?=.*MORTGAGE\b)(?=.*Words used in multiple sections|WORDS USED OFTEN IN THIS DOCUMENT|The date of this Mortgage\b)(?=.*Security Instrument).*|(?=.*\bTHIS MORTGAGE made\b)(?=.*\bWITNESSETH\b).*|(?=.*\bMORTGAGE\b)(?=.*\bTHIS INDENTURE\b)(?=.*made the).*|(?=.*\bThis bond and mortgage\b)(?=.*\bmade the day of\b)(?=.*\bWitnesseth\b).*|(?=.*\bTHIS MORTGAGE\b)(?=.*\bis made this|is given on|is given to|by and between|is made on|entered into this\b).*|(?=.*\bCREDIT MORTGAGE\b)(?=.*Space Above This Line For Recording Data).*|(?=.*\bDOWN PAYMENT ASSISTANCE MORTGAGE\b)(?=.*THIS MORTGAGE).*|(?=.*\bSECURITY DEED\b)(?=.*\bWords used in multiple sections\b)(?=.*Security Instrument).*|(?=.*DOWN PAYMENT ASSISTANCE MORTGAGE\b)(?=.*\bmade and entered\b).*";
为了获得更好的性能,我可以在这里做的是将rule.getRegexes() 中存在的正则表达式合并到一个合并的正则表达式中
最后,我正在为每个规则执行合并的正则表达式。
【问题讨论】:
-
你能提供一个你输入的样本吗?
-
这试图解决的总体问题是什么? 3-4分钟适用于搜索一个文本还是多个文本?
-
看看Aho-Corasick algorithm。它专门用于同时定位输入文本中的多个字符串。
标签: java regex performance java-8