PCRE 正则表达式 到 sed 正则表达式
首先,我很抱歉我的英语不好。我是一个德国人。
下面给出的代码在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
sed 不支持非贪婪正则表达式匹配。
sed does not support non-greedy regex match.
您需要在要引用的括号前面添加反斜杠,因此
You need a backslash in front of the parentheses you want to reference, thus
您必须按如下方式转义块选择器字符
(
和)
。You have to escape the block selector characters
(
and)
as follows.这里有一个解决方案,它并不完美,仅处理多一个“,”或“.”的情况。
here is a solution, it is not prefect, only deal with the situation of one extra "," or "."
如果要匹配文字“.”,则需要对其进行转义或在字符类中使用它。作为削减捕获括号(您需要对基本 RE 执行此操作)的替代方法,您可以使用 -E 选项告诉 sed 使用扩展 RE。最后,sed 使用的 RE 使用
\N
来引用子模式,其中N
是一个数字。这有其自身的问题,将阻止使用两种类型的引号的 href 属性的匹配。
man sed
和man 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, whereN
is a digit.This has its own issue that will prevent matches of href attributes that use both types of quotes.
man sed
andman re_format
will give more information on REs as used in sed.