【问题标题】:Regex to add <span> as child of an anchor tag w/attributes正则表达式将 <span> 添加为带有属性的锚标记的子项
【发布时间】:2021-06-12 00:45:27
【问题描述】:

我需要一个正则表达式来查找和插入带有跨度子项的锚标记。 例如

替换:

<a
            href="https://en.wikipedia.org/wiki/Edward_Seymour,_1st_Duke_of_Somerset"
            title="Edward Seymour, 1st Duke of Somerset"
            >Edward Seymour, 1st Duke of Somerset</a
          >

与:

<a
            href="https://en.wikipedia.org/wiki/Edward_Seymour,_1st_Duke_of_Somerset"
            title="Edward Seymour, 1st Duke of Somerset"
            ><span>Edward Seymour, 1st Duke of Somerset</span></a
          >

搜索将在 VS Code 中进行,因此需要处理换行符和 cr。我已经接近了

(.+?>){1}([a-z])*

【问题讨论】:

标签: html regex visual-studio-code


【解决方案1】:

这并不完美,因为您可能会在彼此之间嵌套锚点,而正则表达式不利于跟踪嵌套上下文。但是一个好的 90% 解决方案是从寻找 的所有内容。然后在一个单独的捕获组中保存所有内容,不包括下一个。最后的捕获组得到 ​​a、一些可选的空格和下一个结束符 >。

string.RegExpReplace("(<a[^>]+?>)(.+?)(</a[\s\r\n]*>)", "$1<span>$2</span>$3", regexOptios.SingleLine)

替换字符串中的 $n 条目指的是捕获的每个组的内容。结果:

<a
        href="https://en.wikipedia.org/wiki/Edward_Seymour,_1st_Duke_of_Somerset"
        title="Edward Seymour, 1st Duke of Somerset"
        ><span>Edward Seymour, 1st Duke of Somerset</span></a
      >

【讨论】:

  • 谢谢。它在尝试 @ regex101.com 时效果很好,但在 Vs Code 中却没有。仅找到未分解为多行的锚标记。我尝试添加 /r/n 但不好。
  • 有几个有用的标志可以设置来告诉正则表达式如何表现。您描述的行为是当多行标志 (/m) 设置为 True 时。确保它为 False,以便将换行符捕获为点说明符的一部分。
  • 很抱歉,我不知道你会怎么做。我尝试将 /m 添加到表达式的末尾,但没有得到任何结果。
  • 我在docs.microsoft.com/en-us/dotnet/api/… 找到了文档。尝试这样调用它 regex.replace(string,"(]+?>)(.+?)(\s*>)", "$1$2$3 ",regexOptions.SingleLine)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2012-12-08
  • 1970-01-01
  • 2010-11-24
相关资源
最近更新 更多