我试图在目录中的所有文件中找出我的具体单词(使用不推荐使用的 API 的方法调用)的所有出现。我需要一个正则表达式来查找所有不包含更新调用(新 API)的此类事件。你能帮我吗?
例子:
- 不推荐使用的 api:方法(a,b,c)
- 新 api: 方法({a:a, b:b, c:c})
正则表达式应该找到所有包含 'method' 但不包含 'method({'.
谢谢你。
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)
解释一下:[ ]
定义了一个字符类——即这个位置的字符可以匹配类内的任何东西。
as 类的^
第一个字符是一个否定:它意味着这个类匹配除了这个类中定义的字符之外的任何字符。
在这种{
情况下,当然是我们关心的唯一不匹配的字符。
因此,在某些情况下,这将匹配任何字符串,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` 在大多数正则表达式实现中)
我想说正确的方法是使用负前瞻运算符,?!
/method(?!\(\{)/
上述声明,“任何发生的method
情况都不会跟随({
”
它比建议/method([^{]/
的更符合您的要求,因为后者与字符串结尾(即 )不匹配abc abc method
,并且它不能很好地处理({
您要求的两个字符的组合。
您可以使用字符类来排除以下内容 {
,例如
/method\([^{]/