Repetition


Many patterns include atoms that repeat multiple times. For example, to match a string with 6 letters one might define the pattern:

\w\w\w\w\w\w

which is both cumbersome, and limits the pattern to only a specific number of characters. What if we wanted to match words with 6 or 7 letters?

This is resolved using quantifiers, which specify how atoms repeat in a pattern. Using quantifiers we could express the previous pattern as:

\w\{6}

which specifies that the "\w" atom is to be repeated 6 times.

Greedy vs Non-greedy

Greedy matching is the default behavior of regular expressions, where the regular expression engine will try to match as much text as possible. In contrast, non-greedy matching, also known as lazy matching, tries to match as little text as possible.

Specifier From To Greedy
* 0 all_inclusive Yes
+ 1 all_inclusive Yes
? 0 1 Yes
= 0 1 Yes
{} 0 all_inclusive Yes
{n,m} n m Yes
{n} n
{n,} n all_inclusive Yes
{,m} 0 m Yes
{-n,m} n m No
{-n} n
{-n,} n all_inclusive No
{-,m} 0 m No
{-} 0 all_inclusive No
Note

? is the standard "0 or 1", but cannot be used in Vim reverse searches. For this reason, Vim additionally defines = as equivalent to ?.