Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java replaceAll function of string does not replace [duplicate]

Tags:

java

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?

like image 278
olidev Avatar asked Apr 20 '26 11:04

olidev


2 Answers

You don't need regex, so use:

test.replace("()", "")
like image 60
Bozho Avatar answered Apr 22 '26 23:04

Bozho


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"
like image 25
aioobe Avatar answered Apr 23 '26 01:04

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!