3

Possible Duplicate:
Wrong output using replaceall

If I have string:

String test = "replace()thisquotes";

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

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

so () is not replaced.

Any ideas?

1
  • I would like to have: replacethisquotes Commented May 26, 2011 at 8:20

6 Answers 6

11

You don't need regex, so use:

test.replace("()", "")
Sign up to request clarification or add additional context in comments.

Comments

2

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"

1 Comment

"the first argument ... needs to be quoted" in addition, the second argument also needs to be quoted for replacement stuff
0

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);
   }
}

Comments

0

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

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

Comments

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

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

Comments

0

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("()"), "");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.