O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a Nongreedy Pattern

Problem

You’re using a regular expression but not seeing the correct results. The pattern is acting greedy, matching more characters than you want it to.

Solution

Replace the regex with a nongreedy version to match the smallest amount of characters possible.

Discussion

Whenever you create a pattern that includes matches for character repetition using the * and + metacharacters or the { n , m } metasequence, the pattern is greedy. A greedy pattern is one that tries to consume as much text as possible, matching the largest substring it can. Patterns are greedy because of the underlying code in the regular expression engine, and understanding how that engine works allows you to create more precise regexes.

Consider that you want to remove HTML tags in a string, as described in Recipe 13.4. Every HTML tag starts with an opening < and ends in a closing >. In between the angle brackets, there could be a wide variety of characters, such a numbers, letters, quotes, the equal sign, etc. For the sake of simplicity, instead of creating a character class for everything that could appear between the < and >, a .* will match “any character, any number of times.” So, you construct the regular expression /<.*>/g and try running it against a string that contains HTML tags:

var example:String = "<b>hello</b>, world!";

// Displays: <b>hello</b>
trace( example.match( /<.*>/g ) );

You might have expected that the regular expression would produce two matches, one for <b>

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required