Vim tip 29: greedy quantifiers
Quantifiers can be applied to literal characters, dot metacharacter, groups, backreferences and character classes.
*
match zero or more timesabc*
matchesab
orabc
orabccc
orabcccccc
but notbc
Error.*valid
matchesError: invalid input
but notvalid Error
s/a.*b/X/
replacestable bottle bus
withtXus
sincea.*b
matches from the firsta
to the lastb
\+
match one or more timesabc\+
matchesabc
orabccc
but notab
orbc
\?
match zero or one times\=
can also be used, helpful if you are searching backwards with the?
commandabc\?
matchesab
orabc
. This will matchabccc
orabcccccc
as well, but only theabc
portions/abc\?/X/
replacesabcc
withXc
\{m,n}
matchm
ton
times (inclusive)ab\{1,4}c
matchesabc
orabbc
orxabbbcz
but notac
orabbbbbc
\{m,}
match at leastm
timesab\{3,}c
matchesxabbbcz
orabbbbbc
but notac
orabc
orabbc
\{,n}
match up ton
times (including0
times)ab\{,2}c
matchesabc
orac
orabbc
but notxabbbcz
orabbbbbc
\{n}
match exactlyn
timesab\{3}c
matchesxabbbcz
but notabbc
orabbbbbc
Greedy quantifiers will consume as much as possible, provided the overall pattern is also matched. That's how the Error.*valid
example worked. If .*
had consumed everything after Error
, there wouldn't be any more characters to try to match valid
. How the regexp engine handles matching varying amount of characters depends on the implementation details (backtracking, NFA, etc).
See :h pattern-overview for more details.
If you are familiar with other regular expression flavors like Perl, Python, etc, you'd be surprised by the use of \
in the above examples. If you use \v
very magic modifier, the \
won't be needed.
Video demo:
See also my Vim Reference Guide and curated list of resources for Vim.