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?
Pass lookaround based regex in
replaceAll
function. Lookarounds won't consume any character but asserts whether a match is possible or not.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.