【问题标题】:Replace dashes with spaces just in anchor text仅在锚文本中用空格替换破折号
【发布时间】:2017-05-22 14:34:14
【问题描述】:

我只想用空格替换锚定 HTML 代码中的破折号,如下所示:

<a href="https://example.com/hello-world-hi">hello-world-hi</a>

替换后是:

<a href="https://example.com/hello-world-hi">hello world hi</a>

如何告诉正则表达式只替换锚文本中的破折号?

【问题讨论】:

  • 使用 perl,:% perldo s/^&lt;a[^&gt;]*&gt;(*SKIP)(*F)|-/ /g 不确定它对 html 标签有多强大...

标签: regex vim sed


【解决方案1】:
  1. 直观地选择该标签的内容:

    vit
    
  2. 对视觉选择覆盖的文本执行替换:

    :s/\%V-\%V/ /g
    

【讨论】:

    【解决方案2】:

    你仍然可以通过替换来做到这一点:

    :%s:\(<a [^>]*>\)\(.\{-}\)\(</a>\):\=join([submatch(1),substitute(submatch(2),'-',' ','g'),submatch(3)],''):g
    

    【讨论】:

    • 这没什么实用的:P
    【解决方案3】:

    您不应该尝试使用正则表达式解析 HTML,而应使用解析器。

    对于命令行处理,有 HTML-XML-utils(为许多 Linux 发行版打包)及其 hxpipehxunpipe 命令,它们将 HTML 转换为易于由基于行的工具处理并返回的格式:

    $ echo '<a href="https://example.com/hello-world-hi">hello-world-hi</a>' | hxpipe
    Ahref CDATA https://example.com/hello-world-hi
    (a
    -hello-world-hi
    )a
    -\n
    

    现在,我们可以修改它,例如使用 GNU sed(&gt; 是辅助提示):

    $ echo '<a href="https://example.com/hello-world-hi">hello-world-hi</a>' |
    > hxpipe |
    > sed '/^(a$/,/^)a$)/{/^-/s/-/ /2g}'
    Ahref CDATA https://example.com/hello-world hi
    (a
    -hello world hi
    )a
    -\n
    

    sed 命令,更好的可读性和注释:

    sed '
        /^(a$/,/^)a$)/{   # If we are within an anchor tag...
            /^-/s/-/ /2g  # If the line starts with "-" (text), replace all but the
        }                 #   first hyphen with a space
    '
    

    hxpipe- 开头的行表示文本,因此我们替换所有连字符除了s///2g 的行为是特定于 GNU sed 的,对于其他 sed 可能会有所不同。

    最后,我们将其“解压”回 HTML:

    $ echo '<a href="https://example.com/hello-world-hi">hello-world-hi</a>' |
    > hxpipe |
    > sed '/^(a$/,/^)a$)/{/^-/s/-/ /2g}' |
    > hxunpipe
    <a href="https://example.com/hello-world hi">hello world hi</a>
    

    【讨论】:

    • 嗯。我基本上同意应该使用 HTML 解析器(我没有投票)。但是这个 hxpipe 的东西看起来很 hackish,尤其是与 sed 结合使用时。一个小的 Python(或其他)程序会更干净。
    • 感谢您介绍这个用于 HTML 解析的工具。瑞士刀结合 sed。
    • @hek2mgl 我猜 sed 只是 always 看起来很老套;)但我才意识到我可以稍微清理一下(不需要循环)。是的,Python/Perl 或类似的东西会更干净,但如果你真的想要一些可管道的东西,我发现 hxpipehxunpipe 对于快速原型和一次性脚本非常有用。
    • 好吧,也许有一天我应该试一试。以前从未听说过 html-xml-utils。谢谢你。
    猜你喜欢
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    相关资源
    最近更新 更多