Java Reference
In-Depth Information
Repetition Characters
Regular expressions include something called repetition characters, which are a means of specifying
how many of the last item or character you want to match. This proves very useful, for example, if you
want to specify a phone number that repeats a character a specifi c number of times. The following table
lists some of the most common repetition characters and what they do.
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
You saw earlier that to match a telephone number in the format 1-800-888-5474, the regular expression
would be \d-\d\d\d-\d\d\d-\d\d\d\d. Let's see how this would be simplifi ed 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, there are 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:
var myRegExp = /\d-\d{3}-\d{3}-\d{4}/
Search WWH ::




Custom Search