Java String Replace '&' with but not with & amp;

I have a large string in which I have the characters available in the following patterns -

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

I want to replace all occurrences and the character with & When replacing this, I must also make sure that I do not mistakenly convert & in & . How do I do this in terms of performance? Am I using regex? If yes, please, can you help me choose the right regular expression to do the above?

I have tried so far without joy:

 data = data.replace(" & ", "&"); // doesn't replace all & data = data.replace("&", "&"); // replaces all &, so & becomes & 
+7
java string regex replace ampersand
source share
2 answers

You can use a regex with a negative representation.

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

Using replaceAll , you will get:

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

So the code for one line of str will be:

 str.replaceAll("&(?!amp;)", "&"); 
+27
source share

You can try this, it should work:

 data = data.replaceAll("&","&").replaceAll("&","&"); 

So you first replace all & & , so all you have is & , and then you replace everything with & .

+2
source share

All Articles