Repeated occurrences
So far, we saw how we can match fixed characters or numeric patterns. Most often, you want to handle certain repetitive natures of patterns also. For example, if I want to match 4 a
s, I can write /aaaa/
, but what if I want to specify a pattern that can match any number of a
s?
Regular expressions provide you with a wide variety of repetition quantifiers. Repetition quantifiers let us specify how many times a particular pattern can occur. We can specify fixed values (characters should appear n times) and variable values (characters can appear at least n times till they appear m times). The following table lists the various repetition quantifiers:
?
: Either 0 or 1 occurrence (marks the occurrence as optional)*
: 0 or more occurrences+
: 1 or more occurrences{n}
: Exactlyn
occurrences{n,m}
: Occurrences betweenn
andm
{n,}
: At least ann
occurrence{,n}
: 0 ton
occurrences
In the following example, we create a pattern where the character u
is optional (has 0 or 1 occurrence):
var...