使用Perl样式语法对两位数字进行Grep

时间:2014-04-27 02:14:38

标签: regex perl grep

所以我正在阅读O' Reilly的正则表达式口袋参考。

我找到了这个例子:

/^\d{1,6}$/

应该匹配任何1-6位数字。

但是,当我尝试在Ubuntu上使用PCRE语法通过grep运行它时,它只匹配 1 数字。

我这样运行:

grep -P "^\d{1,6}^" * 

所以我在Perl中给了它一个镜头,它似乎按预期工作:

$example = 600; 

if($example =~ /^\d{1,6}^/){
     print "Gotcha! \n"; # fires as it should 
} else { 
     print "failed \n"; #doesn't fire
} 

$counterexample = 6000000000000000000000; 

if($counterexample =~ /^d{1,6}$/{ 
     print "This shouldn't be \n"; # does not fire, as intended
} else { 
     print "also correct \n"; # Fires as intended 
} 

那么,不应该用-P标志以相同的方式运行grep吗?

我确定我在这里缺少必要的东西。

更新

将第二个^更正为$

grep -P "^\d{1,6}$" * 

我注意到它似乎适用于像

这样的文件
//example file.txt works as intended 
12
123
12345
1234567

//but this doesn't work 
600 500 20 

// Just matches the first one 

1 个答案:

答案 0 :(得分:2)

以下工作正常:

$ cat > 'test'
qwer
1234
1234567
12
qwer
^C
$ grep -P "^\d{1,6}$" *
test:1234
test:12

您使用了第二个^错误类型,或者您是否真的打算使用它而不是$

<强>更新

为什么它会匹配新的例子? 600 500 20

这些数字之间存在空格,您使用的正则表达式由锚点^$限定,用于行的开头和结尾。如果您希望这些数字匹配,则必须使用单词boundary anchors。 /\b\d{1,6}\b/

换句话说,你的正则表达式正在按预期运行。