Java Reference
In-Depth Information
You saw earlier that to match a telephone number in the format 1‐800‐888‐5474, the regular
expression would be \d‐\d\d\d‐\d\d\d‐\d\d\d\d . Let's see how this would be simplified with the use
of the repetition characters.
The pattern you're looking for starts with one digit followed by a dash, so you need the following:
\d-
Next are three digits followed by a dash. This time you can use the repetition special characters—
\d{3} will match exactly three \d , which is the any‐digit character:
\d-\d{3}-
Next, you have three digits followed by a dash again, so now your regular expression looks like this:
\d-\d{3}-\d{3}-
Finally, the last part of the expression is four digits, which is \d{4} :
\d-\d{3}-\d{3}-\d{4}
You'd declare this regular expression like this:
var myRegExp = /\d-\d{3}-\d{3}-\d{4}/
Remember that the first / and last / tell JavaScript that what is in between those characters is a
regular expression. JavaScript creates a RegExp object based on this regular expression.
As another example, what if you have the string Paul Paula Pauline , and you want to replace
Paul and Paula with George ? To do this, you would need a regular expression that matches both
Paul and Paula .
Let's break this down. You know you want the characters Paul , so your regular expression starts as:
Paul
Now you also want to match Paula , but if you make your expression Paula , this will exclude a
match on Paul . This is where the special character ? comes in. It enables you to specify that the
previous character is optional—it must appear zero (not at all) or one time. So, the solution is:
Paula?
which you'd declare as:
var myRegExp = /Paula?/
position Characters
The third group of special characters includes those that enable you to specify either where the
match should start or end or what will be on either side of the character pattern. For example, you
might want your pattern to exist at the start or end of a string or line, or you might want it to be
 
Search WWH ::




Custom Search