Java字符串用&替换'&' 但不是 & 到 &
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25560332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java String Replace '&' with & but not & to &
提问by sribasu
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?
我想将所有出现的 & 字符&
替换为在替换它时,我还需要确保我没有错误地将 an 转换&
为&
. 我如何以精通性能的方式做到这一点?我使用正则表达式吗?如果是,请您帮我选择正确的正则表达式来执行上述操作吗?
I've tried following so far with no joy:
到目前为止,我一直没有高兴地尝试以下操作:
data = data.replace(" & ", "&"); // doesn't replace all &
data = data.replace("&", "&"); // replaces all &, so & becomes &
采纳答案by khampson
You can use a regular expression with a negative lookahead.
您可以使用带有否定前瞻的正则表达式。
The regex string would be &(?!amp;)
.
正则表达式字符串将是&(?!amp;)
.
Using replaceAll
, you would get:
使用replaceAll
,你会得到:
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
将是:
str.replaceAll("&(?!amp;)", "&");
回答by gleba
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 &
.
这样,您首先将所有内容替换为&
,&
因此您将拥有的只是&
,然后,您将所有内容替换为&
。