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]吗?
首先要了解的是,在字符类中,正则表达式的元字符都没有任何特殊含义。它们在字面上是匹配的。例如,an*将匹配 a*并且不意味着0 or 1重复。同样,()将匹配(and ),并且不会创建capture group.
现在,如果]在字符类中找到 a,则会自动关闭字符类,并且进一步的字符将不是该字符类的一部分。现在,让我们了解上面发生的情况:
在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, ). 请记住,在字符类中,正则表达式的元字符没有任何特殊含义。因此,您不能在角色类中创建组。
[^(ab)]意味着与 完全相反[(ab)]。它匹配任何不包含任何指定字符的字符串。
[ab]和 和一样[^ab]吗?
不,这两个不包括(和)。因此它们差别不大。
我试一试:
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在此示例中浏览这些 cmd:
#create a file with below lines:
abcde
abde
[abcd
abcd]
abc[]foo
abc]bar
[ab]cdef
a(b)cde
你会看到差异,并用我的评论/解释来思考它。