Introducing the RegExp Class


ActionScript 3.0 uses the RegExp class to define regular expressions. There are two basic ways to construct a RegExp object. You can use the RegExp constructor or literal notation (that is, you can type it in directly as you would type a string or a number). Which you choose is mainly a matter of preference and usage. The constructor requires that you pass it at least one parameter specifying the regular expression pattern as a string. The following example constructs a RegExp object that matches any substring that contains between 4 and 8 lowercase alphabetic characters:

var pattern:RegExp = new RegExp("[a-z]{4,8}");


Note that when you want to define a regular expression pattern at runtime, you ought to use the constructor because it allows you to use a string value to define the expression. You can build this string using code, allowing you to create patterns appropriate for the situation at hand.

The literal notation surrounds the regular expression pattern by forward slashes (/). In the case of literal notation, the pattern is not a string and therefore is not surrounded by quotes. The following constructs a RegExp object that matches the same substrings as the preceding example. However, rather than using the constructor, the following example uses literal notation:

var pattern:RegExp = /[a-z]{4,8}/;


Note that when you want to add a backslash to a pattern that you build with the constructor, you'll have to escape the backslash because the constructor requires that you specify the pattern as a string and the backslash character has special meaning within a string. Many regular expression metasequences use backslashes. For example, the \d metasequence matches any digit. The following statement illustrates how to construct a RegExp object that matches any digit. Because the example uses the constructor, it's necessary to escape the backslash.

var pattern:RegExp = new RegExp("\\d");


Because the backslash character doesn't have special meaning within regular expression literal notation, the following is the literal notation equivalent of the preceding example:

var pattern:RegExp = /\d/;


However, because forward slashes have special meaning within regular expression literal notation, you must escape forward slashes. You can escape forward slashes with backslashes. The following matches the literal forward slash character:

var pattern:RegExp = /\//;





Advanced ActionScript 3 with Design Patterns
Advanced ActionScript 3 with Design Patterns
ISBN: 0321426568
EAN: 2147483647
Year: 2004
Pages: 132

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net