Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parenthesis replacement with empty string

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);
 }
like image 608
Erik Nouroyan Avatar asked Mar 10 '19 09:03

Erik Nouroyan


2 Answers

There is a difference between replace and replaceFirst. If your IDE shows you the method signatures, you'll see:

enter image description here

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 "(".

like image 110
Sweeper Avatar answered Oct 09 '22 00:10

Sweeper


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 "(".

like image 38
Eran Avatar answered Oct 09 '22 02:10

Eran