13.0. IntroductionOne of the most powerful features added to ActionScript 3.0 is regular expressions (more commonly known as regexes or regexps). Regular expressions are, put simply, patterns that can be matched against strings. You may be familiar with other types of patterns, such as wildcards (e.g., * and ?), which can be used to match patterns while searching for files. Patterns are also used in Recipe 9.5. Regular expressions support this type of pattern matching, but they are also much more sophisticated. Regular expressions can be useful in many situations. For instance, the patterns can be applied against strings to perform a variety of tasks, including:
The patterns used for regular expressions are built by combining characters that have special meaning and can range from being very simple: [a-zA-Z] to being extremely complex and cryptic, such as this regex for matching a valid IP address: ^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$ Simple patterns, such as .*, are easy to understand, but more complex patterns are difficult to learn and are even harder to implement. Thankfully, every regular expression can be broken down into a plain English description. For example, the simple regular expression .* means "any character repeated any number of times." More complex patterns, such as (A|a)ction(S|s)cript, are no different because they are built by combining simple patterns in various ways. The pattern (A|a)ction(S|s)cript means "either a capital or lowercase 'a', followed by the string 'ction', followed by either a capital or lowercase 's', followed by the string 'cript'," and can be used to find occurrences of "ActionScript" (and subtle variations, such as "actionScript") in a string.
Despite how complex regular expression patterns can be, it's fairly easy to use regular expressions in ActionScript, as you'll soon discover. This chapter focuses on the more common uses of regular expressions within the context of Flash and ActionScript, and by no means is an exhaustive or comprehensive guide. |