grep 和 perl 正则表达式之间的区别?
我对 grep 的正则表达式和 perl 的正则表达式之间的差异有疑问。考虑以下小测试:
$ cat testfile.txt
A line of text
SOME_RULE = $(BIN)
Another line of text
$ grep "SOME_RULE\s*=\s*\$(BIN)" testfile.txt
SOME_RULE = $(BIN)
$ perl -p -e "s/SOME_RULE\s*=\s*\$(BIN)/Hello/g" testfile.txt
A line of text
SOME_RULE = $(BIN)
Another line of text
如您所见,使用正则表达式“SOME_RULE\s*=\s*$(BIN)”,grep 可以找到匹配项,但 perl 无法使用相同的表达式更新文件。我应该如何解决这个问题?
I have a problem with what I think is a difference in grep's regex and perl's regex. Consider the following little test:
$ cat testfile.txt
A line of text
SOME_RULE = $(BIN)
Another line of text
$ grep "SOME_RULE\s*=\s*\$(BIN)" testfile.txt
SOME_RULE = $(BIN)
$ perl -p -e "s/SOME_RULE\s*=\s*\$(BIN)/Hello/g" testfile.txt
A line of text
SOME_RULE = $(BIN)
Another line of text
As you can see, using the regex "SOME_RULE\s*=\s*$(BIN)", grep could find the match, but perl was unable to update the file using the same expression. How should I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Perl 希望对 '(' 和 ')' 进行转义。另外,shell 会吃掉“$”上的“\”,因此您需要:(
或使用单引号——在任何情况下都是强烈建议的。)
Perl wants the '(' and ')' to be escaped. Also, the shell eats the '\' on the '$', so you need:
(or use single quotes--which is highly advisable in any case.)
您需要转义
(
和)
(捕获组)。实际上你在扩展正则表达式中需要它(ERE ):
You need to escape
(
and)
(Capturing group).Actually you need it in Extended Regular Expression(ERE):
如果你想修改使用
If you want to modify use
Perl 的正则表达式语法与 grep 使用的 POSIX 正则表达式不同。在这种情况下,您会遇到 Perl 正则表达式中括号作为元字符的问题 - 它们表示捕获组。
通过更改 Perl 正则表达式,您应该会获得更大的成功:
然后它将匹配源文本中的文字括号。
Perl's regex syntax is different to the POSIX regexes used by grep. In this case, you're falling foul of parentheses being metacharacters in Perl's regexes - they denote a capturing group.
You should have more success by altering the Perl regex:
which will then match the literal parentheses in the source text.