Regex grep:如何使用非捕获组?
我对下面的命令感到困惑Regex grep:如何使用非捕获组?,regex,shell,grep,Regex,Shell,Grep,我对下面的命令感到困惑 $ cat num.txt 1 2 3 1st 2nd 3th $ cat num.txt | grep -Eo '[0-9](?:st|nd|th)?' 我认为它应该输出为 1 2 3 1 2 3 1 2 3 1 2nd 3th 但它的输出为 1 2 3 1 2 3 1 2 3 1 2nd 3th 我做错了什么?谢谢你的帮助。你可以使用: grep -Eo '^[0-9]+' file 1 2 3 1 2 3 或者在grep-p中使用
$ cat num.txt
1
2
3
1st
2nd
3th
$ cat num.txt | grep -Eo '[0-9](?:st|nd|th)?'
我认为它应该输出为
1
2
3
1
2
3
1
2
3
1
2nd
3th
但它的输出为
1
2
3
1
2
3
1
2
3
1
2nd
3th
我做错了什么?谢谢你的帮助。你可以使用:
grep -Eo '^[0-9]+' file
1
2
3
1
2
3
或者在grep-p
中使用lookahead:
grep -Po '[0-9]+(?=st|nd|th)?' file
1
2
3
1
2
3
非捕获组不会阻止任何子字符串出现在整个匹配结果中。它只避免创建捕获(使用组号可访问的单独子字符串)。