2

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?

BladeMight
  • 2,670
  • 2
  • 21
  • 35

2 Answers2

5

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//
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Yoric
  • 1,761
  • 2
  • 13
  • 15
3

Another option is to use negative lookahead:

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

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

anubhava
  • 761,203
  • 64
  • 569
  • 643