O'Reilly logo

Actionscript Cookbook by Joey Lott

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

9.7. Looking for a Pattern Match

Problem

You want to search a string for every match to a pattern.

Solution

Use the custom String.match( ) method.

Discussion

The native ActionScript String class does not provide a match( ) method that allows you to find matches to a pattern within a string. However, the custom RegExp.as file (see Recipe 9.6) adds a match( ) method to the String class.

You should call the match( ) method from a string and pass it a regular expression as a parameter. The method searches the string for all matching substrings and places them in a new array:

// You must include the third-party RegExp.as file from Recipe 9.6.
#include "RegExp.as"

myString = "Twenty twins went toward them";

// Create a new regular expression to perform a case-insensitive match on an entire
// string for any words that begin with "tow" or "tw".
re = new RegExp("\\bt(o)?w[\\w]+\\b", "ig");

// Find all the matches and put them in an array.
matches = myString.match(re);

/* Loop through the array and display the results. The output is:
   Twenty
   twins
   toward
*/
for (var i = 0; i < matches.length; i++) {
  trace(matches[i]);
}

See Also

Recipe 9.6

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