2011-05-26 63 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("()"), "");