Quite confused about `\?` in vim's regex

301 views Asked by At

I'we been trying to do simple substitution in vim, and find out that the \? in vim not works with * or +, saying that (NFA regexp) Can't have a multi follow a multi, in the vim:

i want it to stop here, not here
~
~
~
[NORMAL] ...
:%s/^\(.*\?\)here//

If I remove \? it works, but the it regex matches up to 2nd here.

But with normal regex it works: https://regex101.com/r/iHdxxl/1

Why it isn't possible to use \? with * or \+ in vim?

2

There are 2 answers

0
Yoric On BEST ANSWER

As stated there, you can't add the ? char in vim after the asterisk. To make the search non greedy, you need to use .\{-} instead of .*:

:%s/\(.\{-}\)here//
0
anubhava On

Another option is to use negative lookahead:

:%s/\v^((here)@!.)* here//

\v is used for very magic to avoid escaping all over in regex.