如果我有字符串:
String test = "replace()thisquotes";
test = test.replaceAll("()", "");
测试结果仍然是:test = "replace()thisquotes"
so()不被替换。
任何想法?
如果我有字符串:
String test = "replace()thisquotes";
test = test.replaceAll("()", "");
测试结果仍然是:test = "replace()thisquotes"
so()不被替换。
任何想法?
的replaceAll函数的第一个参数是一个正则表达式。 “(”字符是在正则表达式特殊字符 使用此:
public class Main {
public static void main(String[] args) {
String test = "replace()thisquotes";
test = test.replaceAll("\\(\\)", "");
System.out.println(test);
}
}
你必须逃离()
,因为这些都是常规exressions保留字符:
String test = "replace()thisquotes";
test = test.replaceAll("\\(\\)", "");
test = test.replaceAll("\\(\\)", "").
的Java全部更换使用正则表达式,所以在你的例子中“()”是一个空组,使用转义字符'\“。
正如其他人指出的,你可能想使用String.replace
在这种情况下,因为你不需要正则表达式。
然而,为了参考,使用String.replaceAll
时,第一个参数(这被解释为一个正则表达式)需要被引用,优选通过使用Pattern.quote
:
String test = "replace()thisquotes";
test = test.replaceAll(Pattern.quote("()"), "");
// ^^^^^^^^^^^^^
System.out.println(test); // prints "replacethisquotes"
“第一个参数......需要引用”另外,第二个参数也需要引用替换的东西 – user102008 2011-06-20 09:39:54
你必须引用您字符串首先是因为括号是正则表达式中的特殊字符。看看Pattern.qutoe(String s)
。
test = test.replaceAll(Pattern.quote("()"), "");
我想要:replacethisquotes – olidev 2011-05-26 08:20:43