为什么这个 Grep 表达式找不到有效的正则表达式?

时间:2021-06-14 14:17:11

标签: regex grep

下面的正则表达式用于通过测试文件查找有效的 Amazon Cognito IdentityPool ID,但使用与 grep 相同的表达式找不到有效匹配项,但正则表达式匹配 https://regextester.com 上的测试字符串 正则表达式:(us(-gov)?|ap|ca|cn|eu|sa)-(central|(north|south)?(east|west)?)-\d:[0-9a-f-]+ 甚至简化为 [\w-]+:[0-9a-f-]+。 两个测试字符串都失败,如下所示,但在 Regextester 上匹配。

us-west-1:de3e-e43-aeefe-bd
us-west-2:323-aaa33-a23d-dfe-daf

像这样运行 grep: grep -oEarHn "(us(-gov)?|ap|ca|cn|eu|sa)-(central|(north|south)?(east|west)?)-\\d:[0-9a-f-]+" test.txt

1 个答案:

答案 0 :(得分:1)

您需要将正则表达式中的 \d\\d 更改为 [0-9][[:digit:]]

grep id (iirc) POSIX 正则表达式的默认模式。 \d 来自 PCRE。如果要启用 \d,可以向 grep 添加 -P 标志。这将启用类似 perl 的正则表达式,其中支持 \d。请确保您不能同时使用 -E-P 标志。