sample.txt包含
abcde
abde有谁能解释一下以下命令的输出-
grep '[[ab]]' sample.txt -无输出grep '[ab[]]' sample.txt -无输出grep '[ab[]' sample.txt -输出为abcde,abdegrep '[ab]]' sample.txt -无输出[(ab)]和[^(ab)]是什么意思?它和[ab]和[^ab]一样吗?
发布于 2013-02-15 09:52:19
首先要理解的是,在字符类中,regex的元字符没有任何特殊的含义。它们确实是相配的。例如,*将与*匹配,而不意味着0 or 1重复。同样,()将与(和)相匹配,而不会创建capture group。
现在,如果在一个字符类中找到一个],这将自动关闭该字符类,并且进一步的字符将不再是该字符类的一部分。现在,让我们了解一下上面发生了什么:
在1、2和4中,您的字符类以第一个结束]结束。因此,最后一个结束括号- ],不是字符类的一部分.它必须分开匹配。因此,您的模式将匹配如下所示:
'[[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)]的意思是匹配任何一个(,a,b,)。记住,在字符类中,regex的元字符没有任何特殊的含义.因此,您不能在字符类中创建组。
[^(ab)]的意思与[(ab)]完全相反。它匹配任何不包含指定字符的字符串。
它和
[ab]和[^ab]一样吗?
不是的。这两项不包括(和)。因此,它们几乎没有什么不同。
发布于 2013-02-15 10:00:53
我试试看:
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你会看到不同之处,然后用我的评论/解释来思考。
https://stackoverflow.com/questions/14891871
复制相似问题