Quantifiers

In regular expressions, quantifiers are metacharacters that specify how many times the previous character or group should be matched.

Quantifiers allow you to specify the number of occurrences of a character or group, making it easier to match patterns of varying lengths.

However, it's important to use quantifiers wisely because using them incorrectly can lead to the wrong results.

Regex Quantifier Description
+ + indicates that the previous character must occur at least one or more times.
? ? indicates that the preceding character is optional. It means the preceding character can occur zero or one time.
* Matches zero or more of the preceding character.
{n} Matches exactly n occurrences of the preceding character.
{n,} Matches n or more occurrences of the preceding character.
{n,m} Matches between n and m occurrences of the preceding element

Greedy vs. lazy matching

Regex quantifiers, such as *, +, and ?, can be greedy or lazy. Greedy matching attempts to match as much as possible, while lazy (or non-greedy) matching matches as little as possible.

Let's see how to use quantifiers in regex pattern.

The following uses the + quantifier.

/ /g

The + sign is used to find one or more occurrences of the previous character. So, ‘colou+r' pattern finds ‘colour' and ‘colouuuur' where ‘u' is present at least once between ‘colo' and ‘r'.

The following uses the ? quantifier:

/ /g

The ? acts as an optional quantifier. The u? in the colou?r pattern makes 'u' as an optional char that may come zero or one time but not more.

The following uses the * quantifier:

/ /g

The * quantifier finds zero or more occurrences of the previous character. The colou*r pattern finds all combinations whether u occurred zero, one, or more times.

The following uses {n} and {n,} quantifiers:

/ /g
/ /g

The {1} in colou{1}r finds exactly 1 occurrence of 'u' in the input string, whereas colou{1,}r finds one or more occurrence of 'u'.

/ /g

The colou{1,4}r finds one to four occurrences of 'u' in the input string.