Java Reference
In-Depth Information
How can you find instances of repeated digits and replace them with the word ERROR ? You need to
use the ability to refer to groups in regular expressions.
First, let's define the string as follows:
var myString = "007,007,001,002,002,003,002,004";
Now you know you need to search for a series of one or more number characters. In regular
expressions the \d specifies any digit character, and + means one or more of the previous character.
So far, that gives you this regular expression:
\d+
You want to match a series of digits followed by a comma, so you just add the comma:
\d+,
This will match any series of digits followed by a comma, but how do you search for any series of
digits followed by a comma, then followed again by the same series of digits? Because the digits
could be any digits, you can't add them directly into the expression like so:
\d+,007
This would not work with the 002 repeat. What you need to do is put the first series of digits in a
group; then you can specify that you want to match that group of digits again. You can do this with
\1 , which says, “Match the characters found in the first group defined using parentheses.” Put all
this together, and you have the following:
(\d+),\1
This defines a group whose pattern of characters is one or more digit characters. This group must be
followed by a comma and then by the same pattern of characters as in the first group. Put this into
some JavaScript, and you have the following:
var myString = "007,007,001,002,002,003,002,004";
var myRegExp = /(\d+),\1/g;
myString = myString.replace(myRegExp, "ERROR");
alert(myString);
The alert box will show this message:
ERROR,1,ERROR,003,002,004
That completes your brief look at regular expression syntax. Because regular expressions can get
a little complex, it's often a good idea to start simple and build them up slowly, as in the previous
example. In fact, most regular expressions are just too hard to get right in one step—at least for us
mere mortals without a brain the size of a planet.
If it's still looking a bit strange and confusing, don't panic. In the next sections, you look at the
String object's split() , replace() , search() , and match() methods with plenty more examples of
regular expression syntax.
Search WWH ::




Custom Search