19

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 &
khampson
  • 14,700
  • 4
  • 41
  • 43
sribasu
  • 680
  • 2
  • 6
  • 24

2 Answers2

48

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;)", "&");
khampson
  • 14,700
  • 4
  • 41
  • 43
  • 1
    You can use `&(?![a-z]{1,6};)` so that `•` doesn't turn into `•`, for example. – Matt Mar 26 '19 at 18:53
7

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 &.

gleba
  • 703
  • 1
  • 7
  • 8