Quantifiers

Quantifiers allows a regular expression to match a specified number or range of numbers of either a character, character class or sub pattern.

Quantifiers are enclosed in curly brackets ({ and }) and have the general form {[minimum-occurrences][,[maximum-occurrences]]}

The usage is best explained by example:

{1}

Exactly 1 occurrence

{0,1}

Zero or 1 occurrences

{,1}

The same, with less work;)

{5,10}

At least 5 but maximum 10 occurrences.

{5,}

At least 5 occurrences, no maximum.

Additionally, there are some abbreviations:

* (asterisk)

similar to {0,}, find any number of occurrences.

+ (plus sign)

similar to {1,}, at least 1 occurrence.

? (question mark)

similar to {0,1}, zero or 1 occurrence.

Greed

When using quantifiers with no maximum, regular expressions defaults to match as much of the searched string as possible, commonly known as greedy behavior.

Modern regular expression software provides the means of turning off greediness, though in a graphical environment it is up to the interface to provide you with access to this feature. For example a search dialog providing a regular expression search could have a check box labeled Minimal matching as well as it ought to indicate if greediness is the default behavior.

In context examples

Here are a few examples of using quantifiers:

^\d{4,5}\s

Matches the digits in 1234 go and 12345 now, but neither in 567 eleven nor in 223459 somewhere.

\s+

Matches one or more whitespace characters.

(bla){1,}

Matches all of blablabla and the bla in blackbird or tabla.

/?>

Matches /> in <closeditem/> as well as > in <openitem>.