我想从大文件中提取一些键值对加上它们的前面的文本,但使用的正则表达式运行得非常慢,所以它需要优化。自定义键值对的正则表达式的优化
输入包括被1或2的键 - 值对相当短串,像
one two three/1234==five/5678 some other text
或
one two three/1234==five/5678 some other text four/910==five/1112 more text
使用的(显然不理想的)的正则表达式是
(.*?)\s*([^ /]+)\s*/\s*([\d]+)\s*==\s*([^ /]+)\s*/\s*([\d]+)\s*
(空间可以在字符串中出现在许多领域,因此重复\s*
元素。)
样本代码来测试上述:
public static void main(String[] args) {
String text = "one two three/1234==five/5678 some other text";
text = "one two three/1234==five/5678 some other text four/910==five/1112 more text";
String regex = "(.*?)\\s*([^ /]+)\\s*/\\s*([\\d]+)\\s*==\\s*([^ /]+)\\s*/\\s*([\\d]+)\\s*";
Matcher matcher = Pattern.compile(regex).matcher(text);
int end = 0;
System.out.println("--------------------------------------------------");
while (matcher.find()) {
System.out.println("\"" + matcher.group(1) + "\"");
System.out.println(matcher.group(2) + " == " + matcher.group(3));
System.out.println(matcher.group(4) + " == " + matcher.group(5));
end = matcher.end();
System.out.println("--------------------------------------------------");
}
System.out.println(text.substring(end).trim());
}
输出是键 - 值对,再加上前面的文本(所有提取的字段都是必需的)。例如,对于较长的字符串,输出为:
--------------------------------------------------
"one two"
three == 1234
five == 5678
--------------------------------------------------
"some other text"
four == 910
five == 1112
--------------------------------------------------
more text
换句话说,该matcher.find()
方法1或2轮运行时,根据该字符串是否具有短或长的形式(1或2键 - 值对)。
问题是提取速度很低,有时根据输入字符串的变化,find()
方法需要很长时间才能完成。
对于正则表达式,有没有更好的形式来显着加快处理速度?
在这种情况下,它似乎不是导致速度慢的原因。为什么要找到()慢,为200-300字符长的字符串?无论如何。 :-) – PNS 2014-09-04 09:28:26