tomahim tomahim - 1 month ago 17
Java Question

Replace all occurrences of ";;" in a string in Java

I'm searching for a one line trick to do the following :

I have this string

";;;;"
and want this result
";NULL;NULL;NULL;"
.

I'm doing
myString.replaceAll(";;", ";NULL;");
but the result is
";NULL;;NULL;"
, I guess it find only two occurrences of the pattern, I want it to consider as three occurrences.

What is the best / quickest way to do this ?

Answer

You can use the following code with positive "look-arounds":

System.out.println(
    ";;;;"
    .replaceAll("(?<=;)(?=;)", "NULL")
);

Output

;NULL;NULL;NULL;

Notes

  • Documentation here
  • Essentially, your pattern here is made of two non-capturing groups that look both behind and ahead the capturing point. If both conditions are met ("preceded by ;" and "followed by ;"), the replacement argument ("NULL") will be inserted between the two.