Java字符串替换'&'与& amp; amp;但不是& amp;到& amp; amp; [英] Java String Replace '&' with & but not & to &

查看:613
本文介绍了Java字符串替换'&'与& amp; amp;但不是& amp;到& amp; amp;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大字符串,我有&以下模式中使用的字符 -

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

我想要替换所有出现的&字符到& amp;
在替换它时,我还需要确保我不会错误地转换& amp; & amp; amp; 。我如何以精通业绩的方式做到这一点?我使用正则表达式吗?如果是的话,请你能帮助我选择正确的正则表达式吗?

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 &


推荐答案

您可以将正则表达式与一起使用否定预测

You can use a regular expression with a negative lookahead.

正则表达式字符串将是&(?!amp;)

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

使用 replaceAll ,你会得到:

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

所以单个字符串的代码 str 将是:

So the code for a single string str would be:

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

这篇关于Java字符串替换'&'与& amp; amp;但不是& amp;到& amp; amp;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆