In the last section, you learnt how to match strings with the ‘?’ and the ‘+’ quantifiers:
- The ‘?’ matches the preceding character zero or one time. It is generally used to mark the optional presence of a character.
- The ‘*’ quantifier is used to mark the presence of the preceding character zero or more times. Now, you’ll learn about a new quantifier – the ‘+’.
The ‘+’ quantifier matches the preceding character one or more times. That means the preceding character has to be present at least once for the pattern to match the string.
Thus, the only difference between ‘+’ and ‘*’ is that the ‘+’ needs a character to be present at least once, while the ‘*’ does not.
To summarise, you have learnt the following quantifiers until now :
- ‘?’: Optional preceding character
- ‘*’: Match preceding character zero or more times
- ‘+’: Match preceding character one or more times (i.e. at least once)
But how do you specify a regex when you want to look for a character that appears, say, exactly 5 times, or between 3-5 times? You cannot do that using the quantifiers above.
Hence, the next quantifier that you’ll learn will help you specify occurrences of the preceding character a fixed number of times.
There are four variants of the quantifier that you just saw:
- {m, n}: Matches the preceding character ‘m’ times to ‘n’ times.
- {m, }: Matches the preceding character ‘m’ times to infinite times, i.e. there is no upper limit to the occurrence of the preceding character.
- {, n}: Matches the preceding character from zero to ‘n’ times, i.e. the upper limit is fixed regarding the occurrence of the preceding character.
- {n}: Matches if the preceding character occurs exactly ‘n’ number of times.
Note
that while specifying the {m,n} notation, avoid using a space after the comma, i.e. use {m,n} rather than {m, n}.
An interesting thing to note is that this quantifier can replace the ‘?’, ‘*’ and the ‘+’ quantifier. That is because:
- ‘?’ is equivalent to zero or once, or {0, 1}
- ‘*’ is equivalent to zero or more times, or {0, }
- ‘+’ is equivalent to one or more times, or {1, }
Now, practice some questions on the {m, n} quantifier in the exercise given below.
You’ve learn about all the quantifiers. In the next section, you’ll learn about some miscellaneous concepts related to regular expressions.