要回答您的原始問題:是的,您可以這樣做,並且如果您在循環中多次應用相同的正則表達式,實際上它會比原始代碼更快。你的循環要寫成這樣:
Pattern p1 = Pattern.compile("REGEX1");
Pattern p1 = Pattern.compile("REGEX1");
while (scan.hasNextLine()) {
String myWorkLine = scan.readLine();
myWorkLine = p1.matcher(myWorkLine).replaceAll("replacement1");
myWorkLine = p2.matcher(myWorkLine).replaceAll("replacement2");
...;
}
但是,如果不your're使用正則表達式,作爲第一個例子說明("<tag1>"
),那麼就不要使用String.replaceAll(String regex, String replacement)
,因爲它是比較慢的規律,因爲表達。而是使用String.replace(CharSequence target, CharSequence replacement)
,因爲它不適用於正則表達式,速度更快。
例子:
"ABAP is fun! ABAP ABAP ABAP".replace("ABAP", "Java");
參見:Java Docs for String.replace
這不是很好的改變你的問題是根本,但沒關係,在這裏再次感謝您的正則表達式的答案:
String s1
= "You can <bold>have nice weather</bold>, but <bold>not</bold> always!";
//EDIT: the regex was 'overengineered', and .?? should have been .*?
//String s2 = s1.replaceAll("(.*?)<bold>(.*?)</bold>(.??)", "$1{$2}$3");
String s2 = s1.replaceAll("<bold>(.*?)</bold>", "{$1}");
System.out.println(s2);
輸出: You can {have nice weather}, but {not} always!
這裏的循環這一新的正則表達式,是的,這將是比原來的循環要快:
//EDIT: the regex was 'overengineered'
Pattern p = Pattern.compile("<bold>(.*?)</bold>");
while (scan.hasNextLine()) {
String myWorkLine = scan.readLine();
myWorkLine = p.matcher(myWorkLine).replaceAll("{$1}");
...;
}
編輯:
這裏的Java RegEx syntax constructs
你需要什麼確切的描述?是否需要將所有的''和''分別替換爲'{'和'}'? –
2012-07-05 14:44:46