正则表达式替换&符号,但不是当它们在URL中时

时间:2009-11-05 10:59:05

标签: html regex encoding ampersand

所以我有这个正则表达式:

&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)

匹配文本块中的所有&

但是,如果我有这个字符串:

& & & & & <a href="http://localhost/MyFile.aspx?mything=2&this=4">My Text &</a>
---------------------------------------------------------^

...标记的&amp;也是有针对性的 - 因为我用它来代替&amp;和s&amp;该网址随后变为无效:

http://localhost/MyFile.aspx?mything=2&amp;this=4

D'哦!有没有人知道在网址中的更好的编码方式。

2 个答案:

答案 0 :(得分:4)

不,URL不会变为无效。 HTML代码变为:

<a href="http://localhost/MyFile.aspx?mything=2&amp;this=4">

这意味着现在未正确编码的代码已正确编码,并且链接包含的实际URL为:

http://localhost/MyFile.aspx?mything=2&this=4

所以,这并不是一个问题。代码中的字符被编码,相反,代码现在是正确的。

答案 1 :(得分:0)

在powershell中,可以这样做:

$String ='& & & & & <a href="http://localhost/MyFile.aspx?mything=2&this=4">My Text &</a>'
$String -replace '(?<!<[^<>]*)&', "&amp;"

产量

&amp; &amp; &amp; &amp; &amp; <a href="http://localhost/MyFile.aspx?mything=2&this=4">My Text &amp;</a>

解析正则表达式:

  1. 环顾四周(?&lt;!....)首先验证你没有任何标签
  2. All&amp;然后找到并替换字符串。
相关问题