Java Reference
In-Depth Information
the parenthesis 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 The initial space and ? mean “match zero or one space.” This
is followed by three or four digits ( \d{3,4} )—although U.S. numbers
always have three digits, UK numbers often have four. Then there's
another “zero or one space,” and, finally, 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 because 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 period (note the \ character, because . is a special character in regular expression syntax),
followed by zero or one space, followed by between two and five digits. Putting these four
patterns together, you can construct the entire regular expression, apart from the surrounding
syntax. The regular expression starts with ^ and ends with $ . The ^ character specifies that the
pattern must be matched at the beginning of the string, and the $ character specifies 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, let's look once again at the
isValidTelephoneNumber() function in ch6 _ example6.js :
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 );
}
Note in this case that it is important to set the case‐insensitive flag by adding an i on the end of the
expression definition; otherwise, the regular expression could fail to match the ext parts. Please
also note that the regular expression itself must be on one line in your code—it's shown in multiple
lines here due to the page‐width restrictions of this topic.
Validating a postal Code
We just about managed to check worldwide telephone numbers, but doing the same for postal codes
would be something of a major challenge. Instead, you'll create a function that only checks for
 
Search WWH ::




Custom Search