How do I use non-greedy (lazy) matching in Vim regex?
Answer
/pattern\{-}
Explanation
The \{-} quantifier in Vim regex matches as few characters as possible, unlike * which matches as many as possible (greedy).
How it works
.*matches as much as possible (greedy).\{-}matches as little as possible (non-greedy/lazy)\{-n,m}matches n to m times, preferring fewer
Example
In the text <b>bold</b> and <b>more</b>:
/<b>.*<\/b>matches the entire string (greedy)/<b>.\{-}<\/b>matches only<b>bold</b>(non-greedy)
Tips
\{-}is Vim's equivalent of*?in Perl/PCRE\{-1,}is the non-greedy version of\+(one or more)- Very magic mode:
/\v<b>.{-}<\/b> - Essential for HTML/XML parsing
- Use
\zsand\zefor more precise matching control