1. Computing
Send to a Friend via Email

Regular Expressions

9. Greedy, Reluctant, and Possessive

clr gif

Now that we have introduced the idea of repeatitions within a regular expression the possibility arises of their being more than one way of matching the supplied enter. Let's say that we have the following code:

var mystring = 'raaaaaaad';
var re = /a+/;

This regular expression could match with each 'a' in the string individually, with 'aaaaaaa' in its entirety, or with any combination of different length combinations of 'a' in between. The default action that Javascript (and other languages that understand regular expressions) take in performing the match in this case is to match with the longest possible string of characters that matches the pattern. This longest possible match is what is meant when we refer to greedy matching.

Where we want the match to be on the shortest possible string instead of the longest (called reluctant matching) we need to modify the regular expression slightly to force the expression to find the shortest rather than the longest match. We do this by adding a question mark after the portion of the regular expression we want to perform this reluctant matching.

var mystring = 'raaaaaaad';
var re = /a+?/;

With the question mark in place our regular expression now matches each 'a' individually rather than all together.

The third type of match is the possessive match. A possessive match is one that compares the regular expression to the entire text string and only matches when the whole string satisfies the criteria. A regular expression is converted to match possessively by appending a + symbol to the end of the text. Actually there is little point in defining possessive qualifiers in regular expressions at the present time as both Internet Explorer 6 and Opera 7 do not understand them at all and produce an error while the Mozilla based browsers such as Firefox simply ignore the possessive qualification and treat the expression as greedy.

©2014 About.com. All rights reserved.