Ajax software
Free javascripts
↑
Main Page
Notice that the
\d
metacharacter differs significantly in meaning from the literal characters used in pat-
terns so far. The character
L
in a pattern could match only an uppercase L, but the metacharacter
\d
can
match
any
of the numeric digits
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
, or
9
.
A metacharacter often matches a
class
of characters. In this case, the metacharacter
\d
matches the class
of characters that are numeric digits.
When you have the pattern
\d\d\d
, you know that it matches three successive numeric digits, but it will
match
012
,
234
,
345
,
999
and hundreds of other numbers.
Matching Triple Numeric Digits
Suppose that you want to match a sequence of three numeric digits. In plain English, you might say that you
want to match a three-digit number. A slightly more formal way to express what you want to do is this: Match
a numeric digit. If the first character is a numeric digit, attempt to match the next character as a numeric digit.
If both the characters are numeric digits, attempt to match a third successive numeric digit.
The metacharacter
\d
matches a single numeric digit; therefore, as described a little earlier, you could use
the pattern
\d\d\d
to match three successive numeric digits.
If all three matches are successful, a match for the regular expression pattern has been found.
The test file,
ABC123.txt
, is shown here:
ABC123
A234BC
A23BCD4
Part Number DRC22
Part Number XFA221
Part Number RRG417
For the moment, aim to match only the numeric digits using the pattern
\d\d\d
shown earlier.
This example uses JavaScript, for reasons that will be explained in a moment.
1.
Navigate to the directory that contains the file
ABC123.txt
and
ThreeDigits.html
. Open
ThreeDigits.html
in a web browser.
2.
Click the button labeled Click Here To Enter Text.
3.
When the prompt box opens, enter a string to test. Enter a string copied from
ABC123.txt
.
4.
Click the OK button and inspect the alert box to see if the string that you entered contained a
match for the pattern
\d\d\d
.
Figure A-7 shows the result after entering the string Part Number
RRG417
.
320
Appendix A: Simple Regular Expressions
bapp01.qxd:bapp01 10:47 320
Ajax software
Free javascripts
→