ReplaceAll Java replace function does not replace

Possible duplicate:
Invalid output using replaceall

If I have a line:

String test = "replace()thisquotes";

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

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

so () is not replaced.

Any ideas?

+3
source share
6 answers

You do not need a regex, so use:

test.replace("()", "")
+11
source

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


For reference, however, when used String.replaceAll, the first argument (which is interpreted as a regular expression) should be specified, preferably using Pattern.quote:

String test = "replace()thisquotes";

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

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

replaceAll . "(" - . :

public class Main {

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

You need to exit (), as these are characters reserved for regular expressions:

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

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

0
source

You should quote your line first, because parentheses are special characters in regular expressions. Take a look Pattern.qutoe(String s).

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

All Articles