PCRE 正则表达式 到 sed 正则表达式

发布于 2024-08-18 02:10:52 字数 375 浏览 4 评论 0原文

首先,我很抱歉我的英语不好。我是一个德国人。

下面给出的代码在 PHP 中运行良好:

$string = preg_replace('/href="(.*?)(\.|\,)"/i','href="$1"',$string);

现在 sed 需要相同的代码。我认为应该是:

sed 's/href="(.*?)(\.|\,)"/href="{$\1}"/g' test.htm

但这给了我这个错误:

sed:-e 表达式 #1,字符 36: `s' 命令上的无效引用 \1 右轴

First of all sorry for my bad english. I'm a german guy.

The code given below is working fine in PHP:

$string = preg_replace('/href="(.*?)(\.|\,)"/i','href="$1"',$string);

Now T need the same for sed. I thought it should be:

sed 's/href="(.*?)(\.|\,)"/href="{$\1}"/g' test.htm

But that gives me this error:

sed: -e expression #1, char 36:
invalid reference \1 on `s' command's
RHS

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

凹づ凸ル 2024-08-25 02:10:52

sed 不支持非贪婪正则表达式匹配。

sed does not support non-greedy regex match.

夜血缘 2024-08-25 02:10:52
sed -e 's|href=\"\(.[^"][^>]*\)\([.,]\)\">|href="\1">|g' file
sed -e 's|href=\"\(.[^"][^>]*\)\([.,]\)\">|href="\1">|g' file
贪了杯 2024-08-25 02:10:52

您需要在要引用的括号前面添加反斜杠,因此

sed 's/href="\(.*?\)(.|\,)"/href="{$\1}"/g' test.htm

You need a backslash in front of the parentheses you want to reference, thus

sed 's/href="\(.*?\)(.|\,)"/href="{$\1}"/g' test.htm
雨轻弹 2024-08-25 02:10:52

您必须按如下方式转义块选择器字符

sed 's/href="\(.*?\)\(.|\,\)"/href="{$\1}"/g' test.htm

You have to escape the block selector characters ( and ) as follows.

sed 's/href="\(.*?\)\(.|\,\)"/href="{$\1}"/g' test.htm
短暂陪伴 2024-08-25 02:10:52

这里有一个解决方案,它并不完美,仅处理多一个“,”或“.”的情况。


sed -r -e 's/href="([^"]*)([.,]+)"/href="\1"/g' test.htm

here is a solution, it is not prefect, only deal with the situation of one extra "," or "."


sed -r -e 's/href="([^"]*)([.,]+)"/href="\1"/g' test.htm
淤浪 2024-08-25 02:10:52

如果要匹配文字“.”,则需要对其进行转义或在字符类中使用它。作为削减捕获括号(您需要对基本 RE 执行此操作)的替代方法,您可以使用 -E 选项告诉 sed 使用扩展 RE。最后,sed 使用的 RE 使用 \N 来引用子模式,其中 N 是一个数字。

sed -E "s/href=([\"'])([^\"']*)[.,]\1/href=\1\2\1/i"

这有其自身的问题,将阻止使用两种类型的引号的 href 属性的匹配。

man sedman re_format 将提供有关 sed 中使用的 RE 的更多信息。

If you want to match a literal ".", you need to escape it or use it in a character class. As an alternative to slashing the capturing parentheses (which you need to do with basic REs), you can use the -E option to tell sed to use extended REs. Lastly, the REs used by sed use \N to refer to subpatterns, where N is a digit.

sed -E "s/href=([\"'])([^\"']*)[.,]\1/href=\1\2\1/i"

This has its own issue that will prevent matches of href attributes that use both types of quotes.

man sed and man re_format will give more information on REs as used in sed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文