开发者

Regexp: is it possible to search for string 'string' but not 'string({'

I am t开发者_如何学JAVArying to find out all occurences of my concrete word (method call with deprecated API) in all files in a directory. I need a regexp to find all such occurences which do not contain updated call (new API). Can you help me please?

Example:

  • deprecated api: method(a,b,c)
  • new api: method({a:a, b:b, c:c})

The regexp should find all files containing 'method' but not 'method({'.

Thank you.


I'd say the proper way is to use the negative look-ahead operator, ?!

/method(?!\(\{)/

The above states, "any occurence of method that is not followed by ({"

It meets your requirements better than the suggested /method([^{]/ as the latter does not match string end (i.e. abc abc method) and it doesn't handle the combination of two characters ({ that you requested very well.


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) 

To explain: [ ] defines a character class - ie, the character in this position can match anything inside the class.

The ^ as the first character of the class is a negation: it means that this class matches any character except the characters defined in this class.

The { of course is the only character we care about not matching in this case.

So in some, this will match any string that has the characters method( followed by any character except {.

There are other ways you could do this instead:

betelgeuse:tmp james$ grep "method(\w" test*
test1: method(a,b,c) 
test3: method(a,b,c)

\w in this case is (assuming the C locale) equivalent to [0-9A-Za-z]. If you want to allow an optional space, you could try:

betelgeuse:tmp james$ grep "method([[:alnum:][:space:]]" test*
test1: method(a,b,c) 
test3: method( a, b, c) 
betelgeuse:tmp james$ 

(in grep syntax, [:alnum:] is the same as\w;[:space:]refers to any whitespace character - this is represented as\s` in most regex implementations)


You can use character classes to exclude a following {, e.g.

/method\([^{]/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜