Main Page

Quantifiers

Code Equal To
Matches
\S
[^\t\n\x0B\f\r]
A non-white–space character
\w
[a-zA-Z_0-9]
A word character (all letters, all numbers, and an underscore)
\W
[^a-zA-Z_0-9]
A non-word character
Using predefined classes can make pattern matching significantly easier. Suppose you want to match
three numbers, without using
\d
. Your code looks like this:
var sToMatch = “567 9838 abc”;
var reThreeNums = /[0-9][0-9][0-9]/;
alert(reThreeNums.test(sToMatch)); //outputs “true”
Using
\d
, the regular expression becomes much cleaner:
var sToMatch = “567 9838 abc”;
var reThreeNums = /\d\d\d/;
alert(reThreeNums.test(sToMatch)); //outputs “true”
Quantifiers
Quantifiers enable you to specify how many times a particular pattern should occur. You can specify
both hard values (for example, this character should appear three times) and soft values (for example,
this character should appear at least once but can repeat any number of times) when setting how many
times a pattern should occur.
Simple quantifiers
The following table lists the various ways to quantify a particular pattern.
Code Description
?
Either zero or one occurrence
*
Zero or more occurrences
+
One or more occurrences
{
n
}
Exactly
n
occurrences
{
n
,
m
}
At least
n
but no more than
m
occurrences
{
n,
}
At least
n
occurrences
For example, suppose you want to match words
bread
,
read
, or
red
. Using the question mark quantifier,
you can create just one regular expression to match all three:
var reBreadReadOrRed = /b?rea?d/;
201
Regular Expressions
10_579088 ch07.qxd 3/28/05 11:38 AM Page 201


JavaScript EditorFree JavaScript Editor     Ajax Editor


©