| Programming ActionScript 3.0 > Core ActionScript 3.0 Data Types and Classes > 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.
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.
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. trace(str.match(pattern)); // 337,4, 57, 33
The following methods of the String class take regular expressions as parameters: match(), replace(), search(), and split(). For more information on these methods, see Finding patterns in strings and replacing substrings.
The RegExp class includes the following methods: test() and exec(). For more information, see Methods for using regular expressions with strings.
Flex 2.01