正则表达式:是否可以搜索字符串“string”?但不是 'string({'
我试图找出目录中所有文件中出现的所有具体单词(使用已弃用的 API 的方法调用)。我需要一个正则表达式来查找所有不包含更新调用(新 API)的此类事件。你能帮我吗?
示例:
- deprecated api: method(a,b,c)
- new api: method({a:a, b:b, c:c})
正则表达式应该找到包含“method”但不包含“method({”.
谢谢。
I am trying 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想说正确的方法是使用否定前瞻运算符,
?!
上面指出,“任何
方法
的出现不是 后跟({
"它比建议的
/method([^{]/
更能满足您的要求,因为后者与字符串结尾不匹配(即abc abc 方法
) 并且它不能很好地处理您请求的两个字符({
的组合。I'd say the proper way is to use the negative look-ahead operator,
?!
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.解释一下:
[ ]
定义了一个字符类 - 即该位置的字符可以匹配该类中的任何内容。作为该类的第一个字符的
^
是一个否定:它意味着该类匹配除该类中定义的字符之外的任何字符。{
当然是我们关心的唯一在这种情况下不匹配的字符。因此,在某些情况下,这将匹配任何包含字符
method(
后跟任何字符 除了{
的字符串。您还可以使用其他方法相反:
\w
在这种情况下(假设 C 语言环境)相当于[0-9A-Za-z]
如果您想允许一个可选空格,你可以尝试:(在 grep 语法中,
[:alnum:] 与
\w相同;
[:space:]指任何空白字符 - 这在大多数正则表达式实现中表示为
\s`)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:
\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:(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.