Why doesn't the first line replace "(" with an empty string , while the second one does?
public static void main(String []args){
String a="This(rab)(bar)";
a=a.replace("\\(",""); //First
String b=a.replaceFirst("\\(","");//Second
System.out.println(a + " "+b);
}
There is a difference between replace
and replaceFirst
. If your IDE shows you the method signatures, you'll see:
See how replace
accepts a plain old target
whereas replaceFirst
accepts a regex
?
"\\("
is a regex that means "a single open parenthesis". replace
doesn't treat the strings you pass in as regexes. It will simply try to find a backslash followed by an open parenthesis, which does not exist in your string.
If you want to use replace
, just use "("
.
For replace
to work you should write:
a=a.replace("(",""); //First
or use replaceAll
if you want to pass a regex
:
a=a.replaceAll("\\(",""); //First
replace
accepts a sequence of characters to replace:
public String replace(CharSequence target, CharSequence replacement)
Therefore, in your case it attempts to replace the 3 characters "\(", not just the single character "(".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With