Java String Replace '&' with & but not & to &

sribasu picture sribasu · Aug 29, 2014 · Viewed 45.7k times · Source

I have a large String in which I have & characters used available in following patterns -

A&B
A & B
A& B
A &B
A&B
A & B
A& B
A &B

I want to replace all the occurrences of & character to & While replacing this, I also need to make sure that I do not mistakenly convert an & to &. How do I do that in a performance savvy way? Do I use regular expression? If yes, please can you help me to pickup the right regular expression to do the above?

I've tried following so far with no joy:

data = data.replace(" & ", "&"); // doesn't replace all &
data = data.replace("&", "&");   // replaces all &, so & becomes &

Answer

khampson picture khampson · Aug 29, 2014

You can use a regular expression with a negative lookahead.

The regex string would be &(?!amp;).

Using replaceAll, you would get:

A&B
A & B
A& B
A &B
A&B
A & B
A& B
A &B

So the code for a single string str would be:

str.replaceAll("&(?!amp;)", "&");