使用 grep 正则匹配时不支持 \d

2025-04-07  本文已影响0人  87d6dc4b11a7

使用正则表达式测试匹配Jira Id时,一直无输出。

echo "TEST-58" | grep -oE '^[A-Z]+\-\d+$'

1、在 regex101 验证该表达式是正确的。
2、尝试改成^[A-Z]+-[0-9]+$后,可以正常匹配输出

$ echo "TEST-58" | grep -E '^[A-Z]+-\d+$'
$ echo "TEST-58" | grep -oE '^[A-Z]+-[0-9]+$'
TEST-58

原因分析:
通过man grep查看发现grep 支持的正则表达式,主要有三类,分别是 basic RegExsextended RegExsperl RegExs。其中 basic RegExs 是默认的。

   Pattern Syntax
       -E, --extended-regexp
              Interpret PATTERNS as extended regular expressions (EREs, see below).

       -F, --fixed-strings
              Interpret PATTERNS as fixed strings, not regular expressions.

       -G, --basic-regexp
              Interpret PATTERNS as basic regular expressions (BREs, see below).  This is the default.

       -P, --perl-regexp
              Interpret  I<PATTERNS>  as Perl-compatible regular expressions (PCREs).  This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented
              features.

参考:https://juejin.cn/post/7373860534242656283

上一篇 下一篇

猜你喜欢

热点阅读