开发者

Java replaceAll function of string does not replace [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Wrong output using replaceall

If I have string:

String test = "replace开发者_如何学C()thisquotes";

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

the test result is still: test = "replace()thisquotes"

so () is not replaced.

Any ideas?


You don't need regex, so use:

test.replace("()", "")


As others have pointed out, you probably want to use String.replace in this case as you don't need regular expressions.


For reference however, when using String.replaceAll, the first argument (which is interpreted as a regular expression) needs to be quoted, preferably by using Pattern.quote:

String test = "replace()thisquotes";

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

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


The first argument of replaceAll function is a regular expression. "(" character is a special character in regular expressions. Use this :

public class Main {

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


You have to escape () as these are characters reserved for regular exressions:

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


test = test.replaceAll("\\(\\)", "").

Java replace all uses regular expressions so in your example "()" is an empty group, use escape character '\".


You have to quote your String first because parenthesis are special characters in regular expressions. Have a look at Pattern.qutoe(String s).

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜