betelgeuse:tmp james$ echo " method(a,b,c) "> test1
betelgeuse:tmp james$ echo " method(a,b,c) " > test3
betelgeuse:tmp james$ echo " method({a:a, b:b, c:c})" > test2
betelgeuse:tmp james$ grep "method([^{]" test*
test1: method(a,b,c)
test3: method(a,b,c)
解释一下:[ ] 定义了一个字符类——即这个位置的字符可以匹配类内的任何东西。
^作为类的第一个字符是一个否定:它意味着这个类匹配任何字符除了这个类中定义的字符。
{ 当然是我们唯一关心的在这种情况下不匹配的字符。
所以在某些情况下,这将匹配具有字符method( 后跟任何字符除了 { 的任何字符串。
您可以通过其他方式来代替:
betelgeuse:tmp james$ grep "method(\w" test*
test1: method(a,b,c)
test3: method(a,b,c)
\w 在这种情况下(假设 C 语言环境)等价于[0-9A-Za-z]。如果你想允许一个可选的空间,你可以尝试:
betelgeuse:tmp james$ grep "method([[:alnum:][:space:]]" test*
test1: method(a,b,c)
test3: method( a, b, c)
betelgeuse:tmp james$
(在 grep 语法中,[:alnum:] is the same as\w;[:space:]refers to any whitespace character - this is represented as\s` 在大多数正则表达式实现中)