Java Reference
In-Depth Information
Now you know you need to search for a series of one or more number characters. In regular expressions
the \d specifi es 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? As the digits could be any dig-
its, 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 fi rst series of digits in a group;
then you can specify that you want to match that group of digits again. This can be done with \1, which
says, “Match the characters found in the fi rst group defi ned using parentheses.” Put all this together, and
you have the following:
(\d+),\1
This defi nes 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 fi rst 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 was done 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'll be looking at the
String object's split(), replace(), search(), and match() methods with plenty more examples of
regular expression syntax.
Search WWH ::




Custom Search