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



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

http://regex101.com/r/cI3fG4

基本上,我想匹配最后一个"yo",并保持所有的绿色(组(1))。

这对于小文件/输入很好。

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

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

—Java Code—

    // Works fine for this small snippet but when run against 100k large input
    // as described above some serious perf issues start happening.  
    String text = "Hinnyo keep this herennKeep this herennyonkey match line here cut me:nnAll 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);
    }

试试这个regex:

^([sS]*)byob[sS]*?(cut me:)

没有ms标志。

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

在我的测试中,这证明比你的正则表达式快。(您也可以在regex101的调试器上检查它)

最新更新