Java Reference
In-Depth Information
Now imagine that you change that code, so that you create the RegExp object like this:
var myRegExp = new RegExp("(\b\w+\b) \1");
Why would this not work, and how could you rectify the problem?
exercise 1 Solution
The problem is that the sentence has “has has” and “and and” inside it, clearly a mistake. A lot of
word processors have an autocorrect feature that fixes common mistakes like this, and what your
regular expression does is mimic this feature.
So the erroneous myString :
“This sentence has has a fault and and we need to fix it.”
will become:
“This sentence has a fault and we need to fix it.”
Let's look at how the code works, starting with the regular expression:
/(\b\w+\b) \1/g;
By using parentheses, you have defined a group, so (\b\w+\b) is group 1 . This group matches the
pattern of a word boundary followed by one or more alphanumeric characters, that is, a-z, A-Z,
0-9, and _, followed by a word boundary. Following the group you have a space then \1 . What \1
means is match 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 specified 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 finds 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 finest beer”
Search WWH ::




Custom Search