Chapter 13. Regular Expressions
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 ...
Get ActionScript 3.0 Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.