问题
在grep命令中使用\d匹配数字,但是没有返回任何数据,命令如下:
1 | $ echo test123 | grep 'test\d' |
分析
执行man grep 查看帮助。
Matcher Selection
-E, --extended-regexp
Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. (-F is specified by POSIX.)
-G, --basic-regexp
Interpret PATTERN as a basic regular expression (BRE, see below). This is the default.
-P, --perl-regexp
Interpret PATTERN as a Perl regular expression (PCRE, see below). This is highly experimental and grep -P may warn of unimplemented features.
可以看到grep是支持多种正则表达式的。默认情况下,grep只支持basic regex。\d是perl regex才支持的语法,所以需要使用-P选项。
不同regex的语法区别可以参考:https://www.cnblogs.com/wangkangluo1/archive/2012/04/13/2446021.html
验证
增加-P参数后可以正确匹配数字:
1 | $ echo test123 | grep -P 'test\d' |