【发布时间】:2016-05-03 15:00:52
【问题描述】:
我有一个正则表达式,在找到匹配项时效果很好(500 纳秒),但在没有匹配项时需要很长时间(超过 3 秒)。我怀疑这可能是因为回溯。我尝试了一些选项,例如根据一些文档将.* 转换为(.*)?,但没有帮助。
输入:一个很长的字符串 - 在某些情况下是 5k 个字符。
要匹配的正则表达式:.*substring1.*substring2.*
我正在预编译模式并重新使用匹配器,我还能尝试什么?
这是我的代码 sn-p - 我将使用数百万个不同的输入字符串调用此方法,但只有少数正则表达式模式。
private static HashMap<String, Pattern> patternMap = new HashMap<String, Pattern>();
private static HashMap<String, Matcher> matcherMap = new HashMap<String, Matcher>();
这是我的方法:
public static Boolean regex_match(String line, String regex) {
if (regex == null || line == null) {
return null;
}
if (!patternMap.containsKey(regex)) {
patternMap.put(regex, Pattern.compile(regex));
matcherMap.put(regex,patternMap.get(regex).matcher(""));
}
return matcherMap.get(regex).reset(line).find(0);
}
【问题讨论】:
-
你的目标是什么?你需要使用正则表达式吗?
-
请出示您的代码
-
@Pshemo - 是的,我必须使用正则表达式。
-
是否有需要.*前后的理由?如果您使用 find() 而不是 match() 并去掉表达式上的 .* 前缀和后缀,它应该会快得多。
-
这些模式是硬编码的还是动态构建的?我可以建议使用像
substring1[^s]*(?:s(?!ubstring2)[^s]*)*substring2这样的展开模式