Regular expressions repetition characters specify how many of the last item or character you want to match.
The following table lists some of the most common repetition characters:
Special Character | Meaning | Example |
---|---|---|
{n} | Match n of the previous item. | x{2} matches xx. |
{n,} | Match n or more of the previous item. | x{2,} matches xx, xxx, xxxx, xxxxx, and so on. |
{n,m} | Match at least n and at most m of the previous item. | x{2,4} matches xx, xxx, and xxxx. |
? | Match the previous item zero or one time. | x? matches nothing or x. |
+ | Match the previous item one or more times. | x+ matches x, xx, xxx, xxxx, xxxxx, and so on. |
* | Match the previous item zero or more times. | x* matches nothing, or x, xx, xxx, xxxx, and so on. |
To match a telephone number in the format 1-800-888-1234, the regular expression would be
\d-\d\d\d-\d\d\d-\d\d\d\d.
Let's see how this would be simplified with the use of the repetition characters.
The pattern you're looking for starts with one digit followed by a dash, so you need the following:
\d-
Next are three digits followed by a dash.
This time you can use the repetition special characters-\d{3} will match exactly three \d, which is the any-digit character:
\d-\d{3}-
Next, you have three digits followed by a dash again, so now your regular expression looks like this:
\d-\d{3}-\d{3}-
Finally, the last part of the expression is four digits, which is \d{4}:
\d-\d{3}-\d{3}-\d{4}
You'd declare this regular expression like this:
let myRegExp = /\d-\d{3}-\d{3}-\d{4}/
The first / and last / tell Javascript that what is in between those characters is a regular expression.