Java – 仅在双引号未被转义时才进行转义

huangapple go评论77阅读模式
英文:

Java - Escape double quotes only if not already escaped

问题

给定一个字符串作为输入,我想转义所有那些本应该被转义但实际上没有被转义的双引号。例如,对于给定的输入:
"<?xmlversion=\"1.0"encoding="UTF-8\"?>"
输出应为:"<?xmlversion=\"1.0\"encoding=\"UTF-8\"?>"
我考虑使用正则表达式,但不太确定如何操作。如果有人能帮忙,我将不胜感激。

英文:

Given a String as input, I want to escape all those double quotes that should have escaped but they did not. For instance, given "<?xmlversion=\"1.0"encoding="UTF-8\"?>" as input, the output should be "<?xmlversion=\"1.0\"encoding=\"UTF-8\"?>". I was thinking of using Regex but was not fully sure how. I would appreciate if someone could help with that.

答案1

得分: 0

你可以在这里使用正则表达式替换:

<!-- 语言:java -->

String xml = &quot;&lt;?xmlversion=\\\&quot;1.0\&quot;encoding=\&quot;UTF-8\\\&quot;?&gt;&quot;;
System.out.println(xml);
xml = xml.replaceAll(&quot;(?&lt;!\\\\)\&quot;&quot;, &quot;\\\\\&quot;&quot;);
System.out.println(xml);

这将输出:

<!-- 语言:xml -->

&lt;?xmlversion=\&quot;1.0&quot;encoding=&quot;UTF-8\&quot;?&gt;
&lt;?xmlversion=\&quot;1.0\&quot;encoding=\&quot;UTF-8\&quot;?&gt;

这里使用的正则表达式模式是:

(?&lt;!\\)&quot;

这将匹配所有不在反斜杠前面的双引号,并将它们替换为\&quot;。请注意,在Java的正则表达式语言中,我们必须对反斜杠进行双重转义。此外,文字双引号在Java字符串中变为\&quot;

英文:

You could using a regex replacement here:

<!-- language: java -->

String xml = &quot;&lt;?xmlversion=\\\&quot;1.0\&quot;encoding=\&quot;UTF-8\\\&quot;?&gt;&quot;;
System.out.println(xml);
xml = xml.replaceAll(&quot;(?&lt;!\\\\)\&quot;&quot;, &quot;\\\\\&quot;&quot;);
System.out.println(xml);

This prints:

<!-- language: xml -->

&lt;?xmlversion=\&quot;1.0&quot;encoding=&quot;UTF-8\&quot;?&gt;
&lt;?xmlversion=\&quot;1.0\&quot;encoding=\&quot;UTF-8\&quot;?&gt;

The regex pattern used here is:

(?&lt;!\\)&quot;

This will target all double quotations which are not preceded by a backslash, and replace them with \&quot;. Note that we have to double escape the backslashes within Java's regex language. Also literal double quote becomes \&quot; in a Java string.

huangapple
  • 本文由 发表于 2020年10月20日 12:05:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64438313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定