Chapter 16. Regular Expressions


In This Chapter

Introducing the RegExp Class 252

Working with Regular Expressions 252

Using Regular Expression Flags 255

Understanding Metacharacters and Metasequences 258

Using Regular Expression groups 261

Building a Mad Libs Application Using Regular Expressions 263

Summary 272

Regular expressions enable you to look for substrings that match a pattern, making them a powerful way to work with strings. For basic substring searches, you can use String class methods such as indexOf(). Methods such as indexOf() work when you know the exact substring you want to find. For example, if you want to determine whether a string contains the substring cog you can use the following code:

var string:String = "Gears and cogs"; var index:int = string.indexOf("cog"); trace("contains substring? " + (index != -1));


The preceding code determines whether string contains the letters "cog." If the indexOf() method doesn't return -1, then it means that it found an occurrence of the substring.

When writing sophisticated programs, it's entirely likely that you'll want to search for substrings in a more abstract fashion. For example, consider if you wanted to determine whether a string contains the substring cog or the substring log. In such a case, you could simply test for both substrings using indexOf(). Yet as the number of possible substrings for which you want to test increases, so too does the complexity of the code necessary to test for every substring using indexOf(). If you wanted to test for all substrings that start with a letter followed by og, then you have to test for 52 possible substrings. More complex substring possibilities could require testing for hundreds, thousands, millions, even billions of substrings. This is where regular expressions simplify things greatly.

Regular expressions are a way of testing for substrings by using patterns. Regular expressions use standard characters such as letters and numbers as well as special metacharacters and metasequences to form these patterns. In this chapter, we'll look at how to build and work with regular expressions using ActionScript 3.0.

Note

Regular expressions are supported natively in Flash Player 9 with ActionScript 3.0.





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