User Guide
Finding substrings and patterns in strings 217
Finding matching substrings
The search() method returns the index position of the first substring that matches a given
pattern, as shown in this example:
var str:String = "The more the merrier.";
trace(str.search("the"));
// output: 9
// (This search is case-sensitive.)
You can also use regular expressions to define the pattern to match, as this example shows:
var pattern:RegExp = /the/i;
var str:String = "The more the merrier.";
trace(str.search(pattern)); // 0
The output of the trace() method is 0, because the first character in the string is index
position 0. The
i flag is set in the regular expression, so the search is not case-sensitive.
The
search() method finds only one match and returns its starting index position, even if
the
g (global) flag is set in the regular expression.
The following example shows a more intricate regular expression, one that matches a string in
double quotation marks:
var pattern:RegExp = /"[^"]*"/;
var str:String = "The \"more\" the merrier.";
trace(str.search(pattern));
// output: 4
str = "The \"more the merrier.";
trace(str.search(pattern));
// output: -1
// (Indicates no match, since there is no closing double quotation mark.)
The match() method works similarly. It searches for a matching substring. However, when
you use the global flag in a regular expression pattern, as in the following example,
match()
returns an array of matching substrings:
var str:String = "bob@example.com, omar@example.org";
var pattern:RegExp = /\w*@\w*\.[org|com]+/g;
var results:Array = str.match(pattern);
The results array is set to the following:
["bob@example.com","omar@example.org"]
For more information on regular expressions, see Chapter 10, “Using Regular Expressions,”
on page 285.