Java Reference
In-Depth Information
It's getting better, but it's still not what you want. Notice that the commas after the second and third
Paul substrings have also been replaced because they matched the \W character. Also, you're still not
replacing Paul at the very end of the string. That's because there is no character after the letter l in the
last Paul. What is after the l in the last Paul? Nothing, just the boundary between a word character
and a non-word character, and therein lies the answer. What you want as your regular expression is
Paul followed by a word boundary. Let's alter the regular expression to cope with that by entering the
following:
var myRegExp = /Paul\b/gi;
Now you get the result you want, as shown in Figure 9-11.
Figure 9-11
At last you've got it right, and this example is fi nished.
Covering All Eventualities
Perhaps the trickiest thing about a regular expression is making sure it covers all eventualities. In the
previous example your regular expression works with the string as defi ned, but does it work with the
following?
var myString = “Paul, Paula, Pauline, paul, Paul, JeanPaul”;
Here the Paul substring in JeanPaul will be changed to Ringo . You really only want to convert the
substring Paul where it is on its own, with a word boundary on either side. If you change your regular
expression code to
var myRegExp = /\bPaul\b/gi;
you have your fi nal answer and can be sure only Paul or paul will ever be matched.
Grouping Regular Expressions
The fi nal topic under regular expressions, before you look at examples using the match() , replace() ,
and search() methods, is how you can group expressions. In fact, it's quite easy. If you want a number of
expressions to be treated as a single group, you just enclose them in parentheses, for example, /(\d\d)/ .
Parentheses in regular expressions are special characters that group together character patterns and are
not themselves part of the characters to be matched.
Why would you want to do this? Well, by grouping characters into patterns, you can use the special
repetition characters to apply to the whole group of characters, rather than just one.
Search WWH ::




Custom Search