Java Reference
In-Depth Information
figure 6-6
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 6-7.
At last you've got it right, and this example is finished.
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 defined, but does it work
with the following?
var myString = "Paul, Paula, Pauline, paul, Paul, JeanPaul";