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. |