HTML and CSS Reference
In-Depth Information
Figure H-4
Repetition characters
Regular
Expression
Character
Description
Matches
*
repeat 0 or more times
/\s*/
0 or more consecutive white
space characters
?
repeat 0 or 1 time
/colou?r/
color
or
colour
+
/\s+/
repeat 1 or more times
1 or more consecutive white
space characters
{
n
}
repeat exactly
n
times
/\d{9}/
a nine-digit number
{
n
,}
repeat at least
n
times
/\d{9,}/
a number with at least nine
digits
{
n
,
m
}
repeat at least
n
times but
no more than
m
times
/\d{5,9}/
a number with 5 to 9 digits
Using Escape Sequences
Many commonly used characters are reserved by the regular expression language.
The forward slash character
/
is reserved to mark the beginning and end of a regular
expression literal. The
?
,
+
, and
*
characters are used to specify the number of times a
character can be repeated. What if you need to use one of these characters in a regular
expression? For example, how would you create a regular expression matching the date
pattern
mm/dd/yyyy
when the
/
character is already used to mark the boundaries of the
regular expression?
In these cases, you use an escape sequence. An
escape sequence
is a special com-
mand inside a regular expression that tells the JavaScript interpreter not to interpret
what follows as a character. In the regular expression language, escape sequences are
marked by the backslash character
\
. You have been learning about escape sequences
for several pages now—for example, you saw that the characters
\d
represent a numeric
digit, while d alone simply represents the letter d. The
\
character can also be applied to
reserved characters to indicate their use in a regular expression. For example, the escape
sequence
\$
represents the
$
character while the escape sequence
\\
represents a single
\
character. Figure H-5 provides a list of escape sequences for other special characters.