grep正则表达式空白行为

Mil*_*lde 76 regex grep gnu

我有一个文本文件,包含如下内容:

12,34 EUR 
 5,67 EUR
 ...
Run Code Online (Sandbox Code Playgroud)

在'EUR'之前有一个空格,我忽略0,XX EUR.

我试过了:

grep '[1-9][0-9]*,[0-9]\{2\}\sEUR' => didn't match !

grep '[1-9][0-9]*,[0-9]\{2\} EUR' => worked !

grep '[1-9][0-9]*,[0-9]\{2\}\s*EUR' => worked !

grep '[1-9][0-9]*,[0-9]\{2\}\s[E]UR' => worked !

有人可以解释我请,我为什么不能用\s,但\s*\s[E]匹配?

操作系统:Ubuntu 10.04,grep v2.5

Kam*_*mal 103

这看起来像处理\sgrep 2.5和更新版本之间的行为差异(旧grep中的错误?).我使用grep 2.5.4确认你的结果,但是当使用grep 2.6.3(Ubuntu 10.10)时,你的所有四个greps都能正常工作.

注意:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)
Run Code Online (Sandbox Code Playgroud)

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Run Code Online (Sandbox Code Playgroud)

可能不那么麻烦(\s没有记录):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
Run Code Online (Sandbox Code Playgroud)

我的建议是避免使用\s...使用[ \t]*[[:space:]]或类似的东西来代替.

  • 或者只是`[:space:]`,例如.像这样:`cat file | grep"[[:space:]]"` (21认同)
  • @Milde,我检查过的grep文档(旧的或新的)实际上都没有提到`\ s`.我会说它的行为是"未定义的".使用[:space:]代替,其工作原理如新旧grep中所述. (2认同)