在Vim中,替换/搜索符号中是否存在“匹配的括号/括号/等”?

时间:2021-04-28 17:16:21

I would like to replace for instance every occurrence of "foo{...}" with anything except newlines inside the bracket (there may be spaces, other brackets opened AND closed, etc) NOT followed by "bar".

我想替换每次出现的“foo {...}”除了括号内的换行符(可能有空格,其他括号打开和关闭等),后面跟着“bar”。

For instance, the "foo{{ }}" in "foo{{ }}, bar" would match but not "foo{hello{}}bar".

例如,“foo {{}},bar”中的“foo {{}}”将匹配但不匹配“foo {hello {}} bar”。

I've tried /foo{.*}\(bar\)\@! and /foo{.\{-}}\(bar\)\@! but the first one would match "foo{}bar{}" and the second would match "foo{{}}bar" (only the "foo{{}" part).

我试过/foo{.*}\(bar\)\@!和/foo {。\\ - }}}(bar \)\ @!但第一个匹配“foo {} bar {}”,第二个匹配“foo {{}} bar”(只有“foo {{}”部分)。

2 个解决方案

#1


0  

this regex:

这个正则表达式:

foo{.*}\([}]*bar\)\@!

matches:

火柴:

foo{{ }}
foo{{ }}, bar

but not:

但不是:

foo{hello{}}bar

#2


0  

It is impossible to correctly match an arbitrary level of nested parentheses using regular expressions. However, it is possible to construct a regex to match supporting a limited amount of nesting (I think this answer did not attempt to do so). – Ben

使用正则表达式无法正确匹配任意级别的嵌套括号。但是,可以构造一个正则表达式来匹配支持有限数量的嵌套(我认为这个答案没有尝试这样做)。 - 本

This does ...

这样做......

for up to one level of inner braces:

最多一层内括号:

/foo{[^{}]*\({[^{}]*}[^{}]*\)*}\(bar\)\@!

for up to two levels of inner braces:

最多两层内括号:

/foo{[^{}]*\({[^{}]*\({[^{}]*}[^{}]*\)*}[^{}]*\)*}\(bar\)\@!

for up to three levels of inner braces:

最多三级内括号:

/foo{[^{}]*\({[^{}]*\({[^{}]*\({[^{}]*}[^{}]*\)*}[^{}]*\)*}[^{}]*\)*}\(bar\)\@!

...

...

#1


0  

this regex:

这个正则表达式:

foo{.*}\([}]*bar\)\@!

matches:

火柴:

foo{{ }}
foo{{ }}, bar

but not:

但不是:

foo{hello{}}bar

#2


0  

It is impossible to correctly match an arbitrary level of nested parentheses using regular expressions. However, it is possible to construct a regex to match supporting a limited amount of nesting (I think this answer did not attempt to do so). – Ben

使用正则表达式无法正确匹配任意级别的嵌套括号。但是,可以构造一个正则表达式来匹配支持有限数量的嵌套(我认为这个答案没有尝试这样做)。 - 本

This does ...

这样做......

for up to one level of inner braces:

最多一层内括号:

/foo{[^{}]*\({[^{}]*}[^{}]*\)*}\(bar\)\@!

for up to two levels of inner braces:

最多两层内括号:

/foo{[^{}]*\({[^{}]*\({[^{}]*}[^{}]*\)*}[^{}]*\)*}\(bar\)\@!

for up to three levels of inner braces:

最多三级内括号:

/foo{[^{}]*\({[^{}]*\({[^{}]*\({[^{}]*}[^{}]*\)*}[^{}]*\)*}[^{}]*\)*}\(bar\)\@!

...

...