简体   繁体   English

grep 和 perl 正则表达式之间的区别?

[英]Difference between grep and perl regex?

I have a problem with what I think is a difference in grep's regex and perl's regex.我有一个问题,我认为 grep 的正则表达式和 perl 的正则表达式之间存在差异。 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.如您所见,使用正则表达式“SOME_RULE\\s*=\\s*$(BIN)”,grep 可以找到匹配项,但 perl 无法使用相同的表达式更新文件。 How should I solve this problem?我应该如何解决这个问题?

Perl wants the '(' and ')' to be escaped. Perl 想要转义 '(' 和 ')'。 Also, the shell eats the '\\' on the '$', so you need:此外,外壳会吃掉“$”上的“\\”,因此您需要:

$ perl -p -e "s/SOME_RULE\s*=\s*\\$\(BIN\)/Hello/g" testfile.txt

(or use single quotes--which is highly advisable in any case.) (或使用单引号——在任何情况下都是非常可取的。)

You need to escape ( and ) (Capturing group).您需要逃脱() (捕获组)。

perl -p -e 's/SOME_RULE\s*=\s*\$\(BIN\)/Hello/g' testfile.txt

Actually you need it in Extended Regular Expression( ERE ):实际上你在扩展正则表达式( ERE )中需要它:

grep -E "SOME_RULE\s*=\s*\$\(BIN\)" testfile.txt
perl -ne '(/SOME_RULE\s*?=\s*?\$\(BIN\)/) && print' testfile.txt

如果要修改使用

perl -pe 's/SOME_RULE\s*?=\s*?\$\(BIN\)/Hello/' testfile.txt

Perl's regex syntax is different to the POSIX regexes used by grep. Perl 的正则表达式语法与 grep 使用的 POSIX 正则表达式不同。 In this case, you're falling foul of parentheses being metacharacters in Perl's regexes - they denote a capturing group.在这种情况下,您会遇到 Perl 正则表达式中作为元字符的括号的问题——它们表示捕获组。

You should have more success by altering the Perl regex:您应该通过更改 Perl 正则表达式获得更多成功:

s/SOME_RULE\s*=\s*\$\(BIN\)/Hello/g

which will then match the literal parentheses in the source text.然后将匹配源文本中的文字括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM