正则表达式:替换文件中的空格但仅针对特定标记 (href)

Regex : replace spaces in a file but only target a particular tag (href)

我想更改文件中的空格,但只能在 href=" " 标记内更改。其余文件不应受到影响。有没有一种方法可以直接在正则表达式中完成,比如说 Visual Studio studio,或 Sublime 或您选择的任何其他编辑器

<li><a target="_blank" href="/img/closed-sales/Anderson Ocn Club
2010.pdf" rel="noopener noreferrer">Anderson Ocean Club 2010</a></li>
<li><a target="_blank" href="/img/closed-sales/Anderson ceanClub 2011.pdf" rel="noopener noreferrer">Anderson</a></li>

我试过 href="/.*" ,它基本上匹配 href="" 但我需要替换其中的空格和其他字符,例如 @ 符号。 Fiddle

在 Notepad++ 或 SublimeText 中,您可以利用 \G 构造来匹配从前一个匹配项末尾开始的子字符串,从而将搜索和替换限制在 不同[= 之间的特定文本部分64=] 分隔符。在您的情况下,属性值包含在 " 中,因此您可以使用

(?:\G(?!^)|href="/)[^\s"]*\K\s

并替换为您需要的任何字符。如果不支持 \K 使用

(\G(?!^)|href="/)([^\s"]*)\s

并替换为 [some new text]。这个和前面模式的区别在于(\G(?!^)|href="/)([^\s"]*)匹配的文本也被捕获成一个组,而</code>和<code> 是相应的占位符 (numbered replacement backreferences) that refer to the texts captured with those capturing groups.

在Visual Studio中,您可以使用(?<=href="/[^"]*?)\s代替。

参见 this regex demo

详情

  • (?:\G(?!^)|href="/) - 前一个匹配的开始或 href="/ 子串
  • [^\s"]* - 除了 " 和空格
  • 之外的 0 个或更多字符
  • \K - 匹配重置运算符,从匹配缓冲区中移除所有匹配的文本
  • \s - 一个空白字符。

Sublime Text 3 (Windows):

记事本++:

Visual Studio: