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

Testing Regular Expressions

Problem

You want to test a regex against a string to determine if a match can be made.

Solution

Use the RegExp.test() and RexExp.exec() methods.

Discussion

Recipe 13.1 discusses the building blocks of regular expressions. Once you have created a regular expression that describes the pattern of what you want to find in a string, there are two methods from the RegExp class that can perform the search, test() and exec().

To determine whether a pattern can be matched against a string, use the test() method on a RegExp instance. The test() method takes the string being tested against as the parameter and returns a Boolean value of true if the pattern can be matched, and false otherwise:

// Create a pattern to match against a string
var example:RegExp = /abc/;

// Displays: true
trace( example.test( "A string with abc in it" ) );

// Displays: true
trace( example.test( "abc" ) );

// Displays: false
trace( example.test( "Another string to test against..." ) );

The test() method returns true if the regular expression can be matched anywhere in the string, but it won’t allow you to extract the match or determine where in the string the match was found. To retrieve this information, use the exec() method.

The exec() method works in much the same way that test() does, except that instead of returning a Boolean value, an array is returned containing the substring that matched the pattern. If no match is found, exec() returns null.

// Create a pattern to match against a string ...

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