tomahim tomahim - 1 year ago 99
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

I'm doing
myString.replaceAll(";;", ";NULL;");
but the result is
, 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 Source

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

    .replaceAll("(?<=;)(?=;)", "NULL")




  • 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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download