我有以下输入/输出和regex代码,运行良好(对于下面的输入/输出)。
-投入--
keep this
keep this too
Bye
------ Remove Below ------
remove all of this-产出--
keep this
keep this too
Bye-代码--
String text = "keep this\n \n"
+ " keep this too\n \n Bye\n------ Remove Below ------\n remove all of this\n";
System.out.println(text);
Pattern PATTERN = Pattern.compile("^(.*?)(-+)(.*?)Remove Below(.*?)(-+)(.*?)$",
Pattern.DOTALL);
Matcher m = PATTERN.matcher(text);
if (m.find()) {
// remove everything as expected (from about input->regex->output)
text = ((m.group(1)).replaceAll("[\n]+$", "")).replaceAll("\\s+$", "");
System.out.println(m.group(1));
System.out.println(text);
}好的,这个很好用。但是,这是用于具有定义的输入输出的测试。当我得到必须解析的包含以下字符/模式序列的大型文件时,我看到代码需要一段时间才能对具有以下模式的文件执行(4-5秒)每个Find()方法,即100 k大小的文件。实际上,有时我不确定它是返回还是not...when,但是作为调试测试,find()方法挂起,我的客户端断开连接。
注意:在这个file...but中没有什么可以与之相匹配的,这是一个对我的正则表达式征税的模式。
-100 K档案--
junk here
more junk here
o o o (even more junk per the ellipses)
-------------------------------------this is junk
junk here
more junk here
o o o (even more junk per the ellipses)
-------------------------------------this is junk
junk here
more junk here
o o o (even more junk per the ellipses)
-------------------------------------this is junk
junk here
more junk here
o o o (even more junk per the ellipses)
this repeats from above to make up the 100k file.-问--
我如何优化上面的regex以处理从上面来的大型文件模式,或者对于regex解析速度(4-6秒)来说,这是否是正常的,更不用说完全挂起了?
发布于 2013-12-10 14:47:35
因为您只对------ Remove Below ------行以上的文本感兴趣,所以不需要匹配所有内容。只要通过缩短你的正则表达式来匹配你想要的,避免过多的匹配和回溯。
Pattern PATTERN = Pattern.compile("^(.*?)-+ *Remove Below *-+", Pattern.DOTALL);发布于 2013-12-10 07:19:27
你说得对,这是一场追忆噩梦!
在使用通配符时避免可能的匹配。一些策略,这可能会有帮助:
如果已知“-”的数目,请使用具体字符串测试:
^(.*?)(------ Remove Below ------)(.*)$或者至少更具体一点
^(.*?)-*-\s*Remove Below\s*--*(.*?)$更精确一点:
^(.*?)(-+)([^-]*)Remove Below([^-]*)(-+)(.*?)$如果可以的话,要贪婪:
^(.*)(-+)(.*?)Remove Below(.*?)(-+)(.*?)$如果不需要,不要在匹配中包括:
^(.*?)-+.*?Remove Below.*?-+.*?$当然,根据您的输入质量,您可以将以下概念结合起来:
^(.*)------ Remove Below ------.*$在您的示例中,逐行解析,当它与^.*-+\s*Remove Below\s*-+.*$匹配时,停止修改
发布于 2013-12-10 07:03:34
如果您确定要删除的内容位于文件的末尾,则反转输入字符串。那会对你有很大帮助的。而不是
Matcher m = PATTERN.matcher(text);使用
Matcher m = PATTERN.matcher(new StringBuilder(text).reverse());记住,也要扭转一个模式。
https://stackoverflow.com/questions/20488068
复制相似问题