Erik Nouroyan
Erik Nouroyan

Reputation: 161

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

Upvotes: 6

Views: 1244

Answers (3)

The problem is that it is running in replace with several characters and, therefore, what it will look for is \ and (, so that this does not happen the quotation marks should only contain the character to replace :

    a = a.replace("(", ""); // First

Next I leave a sniper with the original proposal and the fixed one :

public class Main {

    private static final Main initRun = new Main();

    public static void main(String[] args) {

        String a = "This(rab)(bar)";

        System.out.println("Original");
        initRun.runOriginal(a);

        System.out.println("Fixed");
        initRun.runFixed(a);

        // Output
        // Original
        // This(rab)(bar)
        // Thisrab)(bar)
        // Fixed
        // Thisrab)bar)
        // Thisrab)bar)
    }

    /**
     * Execute the original proposal
     *
     * @param a String for replace
     */
    void runOriginal(String a) {
        a = a.replace("\\(", ""); // First
        String b = a.replaceFirst("\\(", "");// Second
        System.out.println(a + "\n" + b);
    }

    /**
     * Execute the fixed proposal
     *
     * @param a String for replace
     */
    void runFixed(String a) {

        a = a.replace("(", ""); // First
        String b = a.replaceFirst("\\(", "");// Second
        System.out.println(a + "\n" + b);
    }
}

Upvotes: 0

Eran
Eran

Reputation: 394126

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

Upvotes: 3

Sweeper
Sweeper

Reputation: 274480

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

Upvotes: 4

Related Questions