正则表达式 - 替换样式标记中的 URL



我在谷歌和stackoverflow上搜索过,但没有找到一个好的答案。我也自己尝试过,但我不是正则表达式大师。

我的目标是将 html 样式标记中的所有相对 url 替换为绝对版本。

例如

  • style="url(/test.png)"style="url(http://mysite.com/test.png)"
  • style="url("/test.png")"style="url("http://mysite.com/test.png")"
  • style="url('/test.png')"style="url('http://mysite.com/test.png')"
  • style="url(../test.png)" style="url(http://mysite.com/test.png)"
  • style="url("../test.png")" style="url('http://mysite.com/test.png')"
  • style="url('../test.png')"style="url('http://mysite.com/test.png')"

等等。

这是我用我可怜的正则表达式"技巧"尝试过的

url((?<Url>[^)]*))

在"URL"功能中给我网址。

提前感谢!

好吧,你可以试试正则表达式:

style="url((['"])?(?:..)?(?<url>[^'"]+)1?)"

并替换为:

style="url($1http://mysite.com$2$1)"

正则表达式101演示

(['"])?将捕获报价(如果存在),并在1?再次使用它们

([^'"]+)将捕获 URL 本身。

最新更新