可能的正则表达式回溯问题?

时间:2014-03-20 04:40:22

标签: java regex

我有以下正则表达式和输入:

http://regex101.com/r/cI3fG4

基本上,我想匹配最后一个“哟”并将所有内容保持为绿色(组(1))。

这适用于小文件/输入。

但是,如果我在java中对一个非常大的(100k)文件运行它,这个文件没有模式匹配(只是一堆文本 - war& peace片段),从尝试返回可能需要10 +秒才能返回找到匹配。我假设正则表达式的回溯问题(特别是(。*)组(1)匹配)。

我可以做些什么来防止每个用例的回溯并加快这个正则表达式以满足上述要求?

- Java代码 -

    // Works fine for this small snippet but when run against 100k large input
    // as described above some serious perf issues start happening.  

    String text = "Hi\n\nyo keep this here\n\nKeep this here\n\nyo\nkey match line here cut me:\n\nAll of this here should be deleted";
    System.out.println(text);
    Pattern PATTERN = Pattern.compile("^(.*)((\\byo\\b.*?(cut me:).*))$",
            Pattern.MULTILINE | Pattern.DOTALL);
    Matcher m = PATTERN.matcher(text);
    if (m.find()) {
        text = m.group(1);
        System.out.println(text);
    }

1 个答案:

答案 0 :(得分:2)

试试这个正则表达式:

^([\s\S]*)\byo\b[\s\S]*?(cut me:)

没有ms标记。

在线演示:http://regex101.com/r/lC9yZ5

在我的测试中,这比你的正则表达式更快。 (您也可以在regex101的调试器上查看