Java Reference
In-Depth Information
So far, you've matching a plus sign (\+) followed by one to three digits (\d{1,3}) and an optional
space ( ?). Remember that since the + character is a special character, you add a \ character in front of it
to specify that you mean an actual + character. The characters are wrapped inside parentheses to spec-
ify a group of characters. You allow an optional space and match this entire group of characters zero or
one times, as indicated by the ? character after the closing parenthesis of the group.
Next is the pattern to match an area code:
(\(\d{1,5}\)|\d{1,5})
This pattern is contained in parentheses, which designate it as a group of characters, and matches either
one to fi ve digits in parentheses ((\d{1,5})) or just one to fi ve digits (\d{1,5}). Again, since the paren-
thesis characters are special characters in regular expression syntax and you want to match actual
parentheses, you need the \ character in front of them. Also note the use of the pipe symbol (|), which
means “OR” or “match either of these two patterns.”
Next, let's match the subscriber number:
?\d{3,4} ?\d{0,7}
Note that there is a space before the fi rst ? symbol: this space and question mark mean “match zero
or one space.“ This is followed by three or four digits ( \d{3,4} ) — although there are always three
digits in the U.S., there are often four in the UK. Then there's another “zero or one space,“ and fi nally
between zero and seven digits (\d{0,7}).
Finally, add the part to cope with an optional extension number:
( (x|xtn|ext|extn|extension)?\.? ?\d{2-5})?
This group is optional, since its parentheses are followed by a question mark. The group itself checks
for a space, optionally followed by x, ext, xtn, extn, or extension, followed by zero or one periods
(note the \ character, since . is a special character in regular expression syntax), followed by zero or
one space, followed by between two and fi ve digits. Putting these four patterns together, you can con-
struct the entire regular expression, apart from the surrounding syntax. The regular expression starts
with ^ and ends with $. The ^ character specifi es that the pattern must be matched at the beginning of
the string, and the $ character specifi es that the pattern must be matched at the end of the string. This
means that the string must match the pattern completely; it cannot contain any other characters before
or after the pattern that is matched.
Therefore, with the regular expression explained, you can now add it to your JavaScript module
ch9_examp7_module.js as follows:
function isValidTelephoneNumber( telephoneNumber )
{
var telRegExp = /^(\+\d{1,3} ?)?
(\(\d{1,5}\)|\d{1,5}) ?\d{3} ?\d{0,7}
( (x|xtn|ext|extn|pax|pbx|extension)?
\.? ?\d{2-5})?$/i
return telRegExp.test( telephoneNumber );
}
Search WWH ::




Custom Search