greptest.txt:
cat sheep
dog money
money cat
ca+
caa
由于
+
不包含在 BRE(POSIX 基本正则表达式)中,因此命令 grep 'ca+' greptest.txt
将其视为纯文本字符,并且所选行符合预期:
ca+
但是,如果我在
\
前面添加 +
,则模式 ca\+
的作用类似于扩展正则表达式,所选行如下:
cat sheep
money cat
ca+
caa
但是,为什么
ca\+
的行为就像没有 grep 命令选项的扩展正则表达式 -E
?
您正在呼叫
grep 'ca\+'
。该标准并未定义 \+
在基本正则表达式中的解释方式。也许这样做是为了允许实现添加扩展,或者也许(通常是这种情况)标准作者必须找到许多现有实现之间的通用功能集。
https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.htmlgnu grep对前面带有未转义字符的普通字符的解释 ( '\' ) 未定义,除了:
The characters ')', '(', '{', and '}' The digits 1 to 9 inclusive (see BREs Matching Multiple Characters) A character inside a bracket expression
的手册页记录了表达式正在使用的语法扩展(如果您使用的是 gnu grep)。
基本正则表达式与扩展正则表达式
In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).