replacing consecutive identical character using replace and replaceAll in Java

512 views Asked by At

I'd like to replace all occurrences of 2 consecutive commas (",,") by a marker in between, but I've found that I can't replace the second occurrence. The code is as follows:

String addresses = "a,,,b";
String b = addresses.replace(",,", ",EMPTYADDR,");
System.out.println(b);

I expect the result to be:

a,EMPTYADDR,EMPTYADDR,b

But instead, I get:

a,EMPTYADDR,,b

How should I change the code to get the desired result?

2

There are 2 answers

0
Avinash Raj On

Pass lookaround based regex in replaceAll function. Lookarounds won't consume any character but asserts whether a match is possible or not.

string.replaceAll("(?<=,)(?=,)", "EMPTYADDR");

DEMO

  • (?<=,) tells the regex engine to lookafter to all the commas.
  • (?=,) tells the regex engine to match all the boundaries which exists after all the commas only if it's followed by another comma.

  • So two boundaries are being matched. By replacing the matched boundaries with EMPTYADDR will give you the desired output.

0
Shar1er80 On

Simple non-Regex method using a while loop

public static void main(String[] args) {
    String addresses = "a,,,b";
    while (addresses.contains(",,")){
        addresses = addresses.replace(",,", ",EMPTYADDR,");
    }
    System.out.println(addresses);
}

Results:

a,EMPTYADDR,EMPTYADDR,b

You could also split the string, fill in the empty elements, and then reconstruct with String.join()

public static void main(String[] args) {
    String addresses = "a,,,b";
    String[] pieces = addresses.split(",");
    for (int i = 0; i < pieces.length; i++) {
        if (pieces[i].isEmpty()) {
            pieces[i] = "EMPTYADDR";
        }
    }

    addresses = String.join(",", pieces);
    System.out.println(addresses);
}