为什么此正则表达式不适用于grep? [英] Why doesn't this regex work for grep?

查看:117
本文介绍了为什么此正则表达式不适用于grep?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从响应中删除"624号数据包不匹配",因此显而易见的尝试是

I'm trying to remove "Packet number 624 doesn't match" from a response so the obvious thing to try is

cat somefile.txt | grep -v "Packet number \d+ doesn't match"

如果我删除了-v,仅用于测试,则它不返回任何内容.因此,也许命令行首先使用\d+做一些事情.因此,我尝试了各种组合,例如\\d+ \\d\+ \\\\d+ \\\\d\+ [0-9]+ [0-9]\+.答对了!!最后一个工作.有人可以解释这里发生了什么吗?如果通过命令行对此进行了修改,为什么echo "\d+"仍返回\d+?

If I remove the -v, just for testing, then it returns nothing. So maybe the command line is doing something with the \d or + first. So I have tried various combinations such as \\d+ \\d\+ \\\\d+ \\\\d\+ [0-9]+ [0-9]\+. Bingo!! That last one worked. Can someone explain what is going on here? If this is getting modified by the command line why does echo "\d+" still return \d+?

推荐答案

默认情况下,grep使用基本正则表达式,而\d是(

By default, grep uses basic regular expression and \d is (PCRE) syntax. It is not supported so you'll need to use ( [0-9] ) or ( [[:digit:]] ) instead, or use grep with option -P

[0-9]+为什么不起作用?

Why doesn't [0-9]+ work?

  • BRE 中,像+这样的元字符失去了含义,需要逃脱.
  • In BRE, meta-characters like + lose their meaning and need to be escaped.

您可以使用以下任一方法解决此问题:

You can fix this by using one of the following:

grep -v "Packet number [0-9]\+ doesn't match"

OR

grep -v "Packet number [[:digit:]]\+ doesn't match"

这篇关于为什么此正则表达式不适用于grep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆