Recipe 9.7 Looking for a Pattern Match

9.7.1 Problem

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

9.7.2 Solution

Use the custom String.match( ) method.

9.7.3 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 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 file from Recipe 9.6.
#include ""

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:
for (var i = 0; i < matches.length; i++) {

9.7.4 See Also

Recipe 9.6

    Part I: Local Recipes
    Part II: Remote Recipes