Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex grep:如何使用非捕获组?_Regex_Shell_Grep - Fatal编程技术网

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

非捕获组不会阻止任何子字符串出现在整个匹配结果中。它只避免创建捕获(使用组号可访问的单独子字符串)。