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

浪子不回头ぞ 提交于 2020-01-23 04:35:09

问题


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 &

回答1:


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;)", "&");



回答2:


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



来源:https://stackoverflow.com/questions/25560332/java-string-replace-with-amp-but-not-amp-to-ampamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!