我想從大文件中提取一些鍵值對加上它們的前面的文本,但使用的正則表達式運行得非常慢,所以它需要優化。自定義鍵值對的正則表達式的優化
輸入包括被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