1. Tech

Your suggestion is on its way!

An email with a link to:

http://javascript.about.com/library/blre08.htm

was emailed to:

Thanks for sharing About.com with others!

Regular Expressions

8. Repetitions

clr gif

So far all we have looked at with regular expressions involves us specifying each character (or list of alternatives) that we want to match. Often what we are trying to match will involve multiple repetitions of the same character (or list of alternatives). Rather than specify the same character over and over we can instead add a quantifier after the character to identify how many times that character is to occur.

var re = /a{5}/;
var re2 = /[a-z]{6}/i;

The first of these examples will match with 'aaaaa' (exactly five lower case 'a' characters together). The second will match any six letter word.

Of course we don't always want a specific number of occurrences and so we can specify a minimum and maximum number instead.

var re = /[a-z]{5,7}/i;

Now we have a regular expression that will match with any five, six, or seven letter combination. If we left off the 7 but included the comma after the 5 then we are indicating that we want it to match at a combination of at least five letters without any upper limit specified so it could match equally well on 155 contiguous alphabetic characters.

There are three combinations that are so commonly required that an alternative notation is supplied to make their coding even shorter.

var re = /ba{0,}b/;
var re2 = /ba*d/;

Both of these regular expressions will match with a 'b' followed by any number of 'a's (or none at all) followed by 'd'.

var re = /ba{1,}b/;
var re2 = /ba+d/;

Both of these regular expressions will match with a 'b' followed by any number of 'a's (at least one) followed by 'd'.

var re = /ba{0,1}b/;
var re2 = /ba?d/;

Both of these regular expressions will match with a 'b' followed by zero or one 'a' followed by 'd'.

©2014 About.com. All rights reserved.