grep 与正则表达式:除非添加断言,否则空格不匹配

发布于 2024-11-28 15:37:56 字数 408 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

俯瞰星空 2024-12-05 15:37:56

查看您的 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 your grep command remains compatible with older versions of grep.

Some systems have egrep with some extensions. Others allow you to use grep -E to get them. Still others have a grep -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.

灰色世界里的红玫瑰 2024-12-05 15:37:56

grep 不支持完整的正则表达式集,因此请尝试使用 -P 启用 Perl 正则表达式。您不需要转义 +

echo "this is a     line" | grep -P 'a\s+line' 

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.

echo "this is a     line" | grep -P 'a\s+line' 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文