Vim tip 29: greedy quantifiers
Quantifiers can be applied to literal characters, dot metacharacter, groups, backreferences and character classes.
*match zero or more timesabc*matchesaborabcorabcccorabccccccbut notbcError.*validmatchesError: invalid inputbut notvalid Errors/a.*b/X/replacestable bottle buswithtXussincea.*bmatches from the firstato the lastb
\+match one or more timesabc\+matchesabcorabcccbut notaborbc
\?match zero or one times\=can also be used, helpful if you are searching backwards with the?commandabc\?matchesaborabc. This will matchabcccorabccccccas well, but only theabcportions/abc\?/X/replacesabccwithXc
\{m,n}matchmtontimes (inclusive)ab\{1,4}cmatchesabcorabbcorxabbbczbut notacorabbbbbc
\{m,}match at leastmtimesab\{3,}cmatchesxabbbczorabbbbbcbut notacorabcorabbc
\{,n}match up tontimes (including0times)ab\{,2}cmatchesabcoracorabbcbut notxabbbczorabbbbbc
\{n}match exactlyntimesab\{3}cmatchesxabbbczbut notabbcorabbbbbc
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.