您不应该尝试使用正则表达式解析 HTML,而应使用解析器。
对于命令行处理,有 HTML-XML-utils(为许多 Linux 发行版打包)及其 hxpipe 和 hxunpipe 命令,它们将 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(> 是辅助提示):
$ 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>