User Guide
286 Using Regular Expressions
Introduction to Regular Expressions
A regular expression describes a pattern of characters. Regular expressions are typically used to
verify that a text value conforms to a particular pattern (such as verifying that a user-entered
phone number has the proper number of digits) or to replace portions of a text value which
match a particular pattern. For example, the following regular expression defines the pattern
consisting of the letters A, B, and C in sequence:
/ABC/
Note that the regular expression literal is delineated with the forward slash (/) character.
Generally, you use regular expressions that match more complicated patterns than a simple
string of characters. For example, the following regular expression defines the pattern
consisting of the letters A, B, and C in sequence followed by any digit:
/ABC\d/
The \d code represents “any digit.” The backslash (\) character is called the escape character,
and combined with the character that follows it (in this case the letter d), it has special
meaning in the regular expression. This chapter describes these escape character sequences
and other regular expression syntax features.
The following regular expression defines the pattern of the letters ABC followed by any
number of digits (note the asterisk):
/ABC\d*/
The asterisk character (*) is a metacharacter. A metacharacter is a character that has special
meaning in regular expressions. The asterisk is a specific type of metacharacter called a
quantifier, which is used to quantify the amount of repetition of a character or group of
characters. For more information, see “Quantifiers” on page 293.
In addition to its pattern, a regular expression can contain flags, which specify how the regular
expression is to be matched. For example, the following regular expression uses the
i flag,
which specifies that the regular expression ignores case sensitivity in matching strings:
/ABC\d*/i
For more information, see “Flags and properties” on page 299.
To search for patterns in strings and to replace characters, you can use regular expressions as
parameters for methods of the String class. For example:
var pattern:RegExp = /\d+/; // matches one or more digits in a sequence
var str:String = "Test: 337, 4, or 57.33.";
trace(str.search(pattern)); // 6
trace(str.match(pattern)); // 337
var pattern:RegExp = /\d+/g; // The g flag makes the match global.