grep 与正则表达式:除非添加断言,否则空格不匹配
GNU grep 2.5.4 on bash 4.1.5(1) on Ubuntu 10.04
这匹配
$ echo "this is a line" | grep 'a[[:space:]]\+line'
this is a line
但这不匹配
$ echo "this is a line" | grep 'a\s\+line'
但这也匹配
$ echo "this is a line" | grep 'a\s\+\bline'
this is a line
我不明白为什么#2不匹配(而#1匹配)并且#3也显示匹配。这里有什么区别?
GNU grep 2.5.4 on bash 4.1.5(1) on Ubuntu 10.04
This matches
$ echo "this is a line" | grep 'a[[:space:]]\+line'
this is a line
But this doesn't
$ echo "this is a line" | grep 'a\s\+line'
But this matches too
$ echo "this is a line" | grep 'a\s\+\bline'
this is a line
I don't understand why #2 does not match (whereas # 1 does) and #3 also shows a match. Whats the difference here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看您的
grep
联机帮助页。 Perl 添加了许多原始规范中没有的正则表达式扩展。然而,由于它们被证明非常有用,许多程序都采用了它们。不幸的是,
grep
有时会停留在过去,因为您希望确保grep
命令与旧版本的grep
保持兼容。有些系统有
egrep
和一些扩展。其他允许您使用 grep -E 来获取它们。还有一些有grep -P
允许您使用 Perl 扩展。我相信Linux系统的grep命令可以使用大多数Unix系统中不可用的-P
扩展,除非有人用GNU版本替换了grep。较新版本的 Mac OS X 也支持-P
开关,但较旧版本不支持。Take a look at your
grep
manpage. Perl added a lot of regular expression extensions that weren't in the original specification. However, because they proved so useful, many programs adopted them.Unfortunately,
grep
is sometimes stuck in the past because you want to make sure yourgrep
command remains compatible with older versions ofgrep
.Some systems have
egrep
with some extensions. Others allow you to usegrep -E
to get them. Still others have agrep -P
that allows you to use Perl extensions. I believe Linux systems' grep command can use the-P
extension which is not available in most Unix systems unless someone has replaced the grep with the GNU version. Newer versions of Mac OS X also support the-P
switch, but not older versions.grep
不支持完整的正则表达式集,因此请尝试使用-P
启用 Perl 正则表达式。您不需要转义+
即grep
doesn't support the complete set of regular expressions, so try using-P
to enable perl regular expressions. You don't need to escape the+
i.e.