Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 &
like image 878
sribasu Avatar asked Aug 29 '14 01:08

sribasu


2 Answers

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;)", "&");
like image 142
khampson Avatar answered Oct 20 '22 13:10

khampson


You can try this, it should work:

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

That way you first replace all & with & so all you'll have is &, and then, you replace all of them with &.

like image 24
gleba Avatar answered Oct 20 '22 13:10

gleba