2013-02-15 75 views
2

sample.txt包含grep的歧义嵌套方括号

abcde 
abde 

任何人都可以解释如下命令的输出 -

  1. grep '[[ab]]' sample.txt - 无输出
  2. grep '[ab[]]' sample.txt - 无输出
  3. grep '[ab[]' sample.txt - 输出是abcdeabde
  4. grep '[ab]]' sample.txt - 无输出

又是什么[(ab)][^(ab)]是什么意思?是否与[ab][^ab]相同?

回答

4

首先要理解的是,在字符类中,没有任何正则表达式的元字符有任何特殊的含义。它们从字面上匹配。例如,*将匹配*,并不意味着0 or 1重复。同样,()将匹配(),并且不会创建capture group

现在,如果在字符类中找到],它会自动关闭字符类,而另一个字符将不是该字符类的一部分。现在,让我们了解什么是上面发生的事情:


124,你的性格类在第一关闭]结束。所以,最后的右括号 - ],不是字符类的一部分。它必须分开配对。所以,你的模式将匹配是这样的:现在

'[[ab]]' is same as '([|a|b)(])' // The last `]` has to match. 
'[ab[]]' is same as '(a|b|[)(])' // Again, the last `]` has to match. 
'[ab]]' is same as '(a|b|])(])' // Same, the last `]` has to match. 
    ^
    ^---- Character class closes here. 

,因为在这两个字符串,没有]末,因此没有发现匹配。

而在第三种模式中,只有最后一个]才会关闭您的角色等级。因此,一切都进入角色类。

'[ab[]' means match string that contains 'a', or 'b', or '[' 

这是完全有效的并匹配两个字符串。


又是什么[(ab)][^(ab)]是什么意思?

[(ab)]指符合任何(ab)。请记住,在字符类中,正则表达式的元字符没有任何特殊含义。所以,你不能在角色类中创建组。

[^(ab)]表示与[(ab)]完全相反。它匹配任何不包含任何指定字符的字符串。


是不是一样[ab][^ab]

不。这两个不包括()。因此他们有点不同。

2

我试试看:

grep '[[ab]]' - match string which has one of "[,a,b" and then a "]" char followed 
grep '[ab[]]' - match string which has one of "a,b,[" and then a "]" char followed 
grep '[ab[]' - match string which has one of "a,b,[" 
grep '[ab]]' - match string which has one of "a,b" and then a "]" char followed 
grep '[(ab)]' - match string which has one of "(,a,b,)" 
grep '[^(ab)]' - match string which doesn't contain "(,a,b" and ")" 
grep '[ab]' - match string which contains one of "a,b" 
grep '[^ab]' - match string which doesn't contain "a" and "b" 

你可以通过这些grep CMDS这个例子:

#create a file with below lines: 
abcde 
abde 
[abcd 
abcd] 
abc[]foo 
abc]bar 
[ab]cdef 
a(b)cde 

,你会看到其中的差别,想想它与我的意见/解释。