Java Reference
In-Depth Information
exactly the same characters as were matched in pattern group 1. So, for example, if group 1 matched
“has,” then \1 will match “has” as well. It's important to note that \1 will match the exact previous
match by group 1. So when group 1 then matches the “and,” the \1 now matches “and” and not the
“has” that was previously matched.
You use the group again in your replace() method; this time the group is specifi ed using the $
symbol, so $1 matches group 1. It's this that causes the two matched “has” and “and” to be replaced by
just one.
Turning to the second part of the question, how do you need to change the following code so that it
works?
var myRegExp = new RegExp(“(\b\w+\b) \1”);
Easy; now you are using a string passed to the RegExp object's constructor, and you need to use two
slashes (\\) rather than one when you mean a regular expression syntax character, like this:
var myRegExp = new RegExp(“(\\b\\w+\\b) \\1”,”g”);
Notice you've also passed a g to the second parameter to make it a global match.
Exercise 2 Question
Write a regular expression that fi nds all of the occurrences of the word “a” in the following sentence and
replaces them with “the”:
“a dog walked in off a street and ordered a fi nest beer”
The sentence should become:
“the dog walked in off the street and ordered the fi nest beer”
Exercise 2 Solution
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script language=”JavaScript” type=”text/javascript”>
var myString = “a dog walked in off a street and ordered a finest beer”;
var myRegExp = /\ba\b/gi;
myString = myString.replace(myRegExp,”the”);
alert(myString);
</script>
</body>
</html>
Save this as ch09_q2.htm.
Search WWH ::




Custom Search