Java Reference
In-Depth Information
How could you match both
JavaScript
and
VBScript
using the same regular expression? The only
thing they have in common is that they are whole words and they both end in
Script
. Well, an easy
way would be to use parentheses to group the patterns
Java
and
VB
. Then you can use the
?
special
character to apply to each of these groups of characters to make the pattern match any word having
zero or one instance of the characters
Java
or
VB
, and ending in
Script
:
var myRegExp = /\b(VB)?(Java)?Script\b/gi;
Breaking down this expression, you can see the pattern it requires is as follows:
1.
A word boundary
:
\b
2.
Zero or one instance of VB
:
(VB)?
3.
Zero or one instance of Java
:
(Java)?
4.
The characters
Script
:
Script
5.
A word boundary
:
\b
Putting these together, you get this:
var myString = "JavaScript, VBScript and PHP";
var myRegExp = /\b(VB)?(Java)?Script\b/gi;
myString = myString.replace(myRegExp, "xxxx");
alert(myString);
The output of this code is shown in Figure 6-8.
figure: 6-8