2011-05-26 66 views

回答

11

你不需要正則表達式,所以使用:

test.replace("()", "") 
+0

是的,這是真的。謝謝! – olidev 2011-05-26 12:07:22

0

的replaceAll函數的第一個參數是一個正則表達式。 「(」字符是在正則表達式特殊字符 使用此:

public class Main { 

    public static void main(String[] args) { 
     String test = "replace()thisquotes"; 
     test = test.replaceAll("\\(\\)", ""); 
     System.out.println(test); 
    } 
} 
0

你必須逃離(),因爲這些都是常規exressions保留字符:

String test = "replace()thisquotes"; 
test = test.replaceAll("\\(\\)", ""); 
0
test = test.replaceAll("\\(\\)", ""). 

的Java全部更換使用正則表達式,所以在你的例子中「()」是一個空組,使用轉義字符'\「。

2

正如其他人指出的,你可能想使用String.replace在這種情況下,因爲你不需要正則表達式。


然而,爲了參考,使用String.replaceAll時,第一個參數(這被解釋爲一個正則表達式)需要被引用,優選通過使用Pattern.quote

String test = "replace()thisquotes"; 

test = test.replaceAll(Pattern.quote("()"), ""); 
//      ^^^^^^^^^^^^^ 

System.out.println(test); // prints "replacethisquotes" 
+0

「第一個參數......需要引用」另外,第二個參數也需要引用替換的東西 – user102008 2011-06-20 09:39:54

0

你必須引用您字符串首先是因爲括號是正則表達式中的特殊字符。看看Pattern.qutoe(String s)

test = test.replaceAll(Pattern.quote("()"), "");