正则表达式用于替换 & 符号,但当它们位于 URL 中时则不替换

发布于 2024-08-10 07:29:28 字数 534 浏览 5 评论 0原文

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

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

匹配文本块中的所有 &

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

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

... 标记的 &也得到了目标 - 因为我用它来替换 & 与 &然后该网址就无效了:

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

D'oh!有谁知道更好的方法来编码不在网址中的&。

So I have this regex:

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

That matches all &'s in a block of text

However, if I have this string:

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

... the marked & also get's targeted - and as I'm using it to replace the &'s with & the url then becomes invalid:

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

D'oh! Does anyone know of a better way of encoding &'s that are not in a url.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

熊抱啵儿 2024-08-17 07:29:29

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

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

这意味着之前没有正确编码的代码现在已经被正确编码了,链接包含的实际 URL 是:

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

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

No, the URL does not become invalid. The HTML code becomes:

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

This means that the code that was not correctly encoded now is correctly encoded, and the actual URL that the link contains is:

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

So, it's not a problem that the & character in the code gets encoded, on the contrary the code is now correct.

没有心的人 2024-08-17 07:29:29

在 powershell 中,可以这样做:

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

产生

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

剖析正则表达式:

  1. 环顾四周 (?
  2. All & 中然后找到并替换字符串。

In powershell this could be done as:

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

yields

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

Dissecting the regex:

  1. The look around (?<! .... ) first validates that you're not in any tag
  2. All & strings are then found and replaced.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文