↑
Main Page
Simple Patterns
Simple Patterns
The patterns used in this chapter so far have all been simple, constructed of string literals. However, a
regular expression has many more parts than just matching specific characters. Metacharacters, charac-
ter classes, and quantifiers are all important parts of regular expression syntax and can be used to
achieve some powerful results.
Metacharacters
In the previous section you discovered that a comma has to be escaped (preceded with a backslash) to
be matched correctly. That’s because the comma is a
metacharacter
, which is a character that is part of
regular expression syntax. Here are all the regular expression metacharacters:
( [ { \ ^ $ | ) ? * + .
Any time you want to use one of these characters inside of a regular expression, they must be escaped.
So, to match a question mark, the regular expression looks like this:
var reQMark = /\?/;
Or like this:
var reQMark = new RegExp(“\\?”);
Did you notice the two backslashes in the second line? This is an important concept to grasp: When a
regular expression is represented in this (non-literal) form, every backslash must be replaced with two
backslashes because the JavaScript string parser tries to interpret
\?
the same way it tries to interpret
\n
.
To ensure that this doesn’t happen, place two backslashes (called
double escaping
) in front of the
metacharacter in question. This little
gotcha
is why many developers prefer to use the literal syntax.
Using special characters
You can represent characters by using their literals or by specifying a character code using either their
ASCII code or Unicode code. To represent a character using ASCII, you must specify a two-digit hexa-
decimal code preceded by
\x
. For example, the character
b
has an ASCII code of 98, which is equal to
hex 62; therefore, to represent the letter
b
you could use
\x62
:
var sColor = “blue”;
var reB = /\x62/;
alert(reB.test(sColor)); //outputs “true”
In both of these methods, you may not see the advantage of using regular expres-
sions in place of simple strings. Keep in mind that the examples in this section of
the chapter are very simple and are used just for introducing concepts; more com-
plex patterns are discussed later and will truly show the power of using regular
expressions in place of simple strings.
197
Regular Expressions
10_579088 ch07.qxd 3/28/05 11:38 AM Page 197
Free JavaScript Editor
Ajax Editor
©
→