【发布时间】:2019-10-11 01:34:24
【问题描述】:
我正在编写一个字符串解析器,用于解析文本文件中的所有字符串,字符串可以在单引号或双引号内,很简单吧?不是真的。我写了一个正则表达式来匹配我想要的字符串。但它在大字符串上给了我StackOverFlow 错误(我知道 java 对大字符串上的正则表达式并不是很好),这是正则表达式模式 (['"])(?:(?!\1|\\).|\\.)*\1
这对我需要的所有字符串输入都很有效,但是一旦有一个大字符串就会抛出 StackOverFlow 错误,我已经阅读了基于此的类似问题,例如 this 建议使用 @987654325 @,但在 '""'、"\\\"" 等字符串上会失败
所以我的问题是我应该怎么做才能解决这个问题?如果需要,我可以提供更多上下文,请发表评论。
编辑:测试答案后
代码:
public static void main(String[] args) {
final String regex = "'([^']*)'|\"(.*)\"";
final String string = "local b = { [\"\\\\\"] = \"\\\\\\\\\", [\"\\\"\"] = \"\\\\\\\"\", [\"\\b\"] = \"\\\\b\", [\"\\f\"] = \"\\\\f\", [\"\\n\"] = \"\\\\n\", [\"\\r\"] = \"\\\\r\", [\"\\t\"] = \"\\\\t\" }\n" +
"local c = { [\"\\\\/\"] = \"/\" }";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
输出:
Full match: "\\"] = "\\\\", ["\""] = "\\\"", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
Group 1: null
Group 2: \\"] = "\\\\", ["\""] = "\\\"", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t
Full match: "\\/"] = "/"
Group 1: null
Group 2: \\/"] = "/
它没有正确处理转义的引号。
【问题讨论】:
标签: java regex string pattern-matching