java - 正则表达式不给出溢出错误

标签 java regex

示例代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {
    public static void main(String[] args) {
        String data = "Shyam and you. You are 2.3 km away from home. Lakshmi and you. Ram and you. You are Mike. ";
        Pattern pattern = Pattern.compile(
                "\\s*((?:[^\\.]|(?:\\w+\\.)+\\w)*are.*?)(?:\\.\\s|\\.$)",
                Pattern.DOTALL);
        Matcher matcher = pattern.matcher(data);
        while (matcher.find()) {
            System.out.println(matcher.group(0));
        }
    }
}

输出:

You are 2.3 km away from home. 

You are Mike. 

我在执行上面的代码时得到了预期的输出。 但问题是当用更大的字符串测试同一个正则表达式时,它显示溢出错误。 我进行了大致相同的搜索,发现正则表达式中的 (A|B)* 之类的交替会导致问题。 有什么办法可以解决这个问题吗? 请帮忙。

最佳答案

我已尝试重构您的正则表达式以避免回溯。你能试试这个正则表达式吗:

Pattern pattern = Pattern.compile("(?>[^.]|(?:\\w+\\.)+\\w)+\\sare\\s.*?(?>\\.\\s|\\.$)",
                  Pattern.DOTALL);

(?>group) 称为原子分组

根据:http://www.regular-expressions.info/atomic.html

原子分组

An atomic group is a group that, when the regex engine exits from it, automatically throws away all backtracking positions remembered by any tokens inside the group. Atomic groups are non-capturing. The syntax is (?>group).

关于java - 正则表达式不给出溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18490835/

相关文章:

java - 使用maven获取多个JSP应用程序的版本信息

java - 将事件发布到单个微服务实例

java - Eclipse 使用哪种 JPA 实现?

Java简单正则表达式错误

java - 如何编写正则表达式 "word character"的 CharMatcher 等效项?

javascript - 用于在 Javascript 中替换具有一种标记类型的字符串的正则表达式

java - org.openqa.selenium.ElementClickInterceptedException : element click intercepted error using Selenium and Java in headless mode

java - 同时写入和读取同一个文件并通过 Jersey 流式传输

regex - 将行尾 (EOL) 与 vim 中的语法匹配

javascript - 用空格替换单引号和其他符号