13.0.
Introduction
One 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:
-
Finding substrings beginning with a vowel (a, e,
i, o, or u)
-
Extracting specific values within a string, such
as the year value from a full date
-
Validating user input to ensure an email address
is formatted correctly
-
Stripping out HTML tags from a block of text to
remove the markup
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.
|
Mastering the syntax of regular expressions is
not trivial. As with anything else, a little effort to learn the
basic principles can go a long way, and knowing and understanding
regular expressions is a powerful tool to have at your
fingertips.
To learn more about regular expressions, you
should get a copy of Mastering Regular
Expressions, by Jeffrey E.F. Friedl (O'Reilly), or
Regular Expressions Pocket
Reference, by Tony Stubblebine (O'Reilly). Both books teach
you everything you need to know about regexes.
|
|
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.
|