Regular Expressions In Flash

Flash CS3′s addition of regular expressions gives you tons of control over your text in flash. For anyone who has experience with regexp this will seem trivial but for those just starting out I hope this example will prove useful. The example is for processing specific data out of an HTML page because there isn’t a REST service for this data.
First, you pull in the HTML document using URLLoader. The data of the URLLoader will be treated as plain text making it perfect to process with a RegExp.

//Create a request for the weather page
var myURLRequest:URLRequest = new URLRequest("http://www.weatheroffice.gc.ca/marine/marine_e.html?46146");
//Load the weather page into a urlloader object.
var myURLLoader:URLLoader = new URLLoader(myURLRequest);
//Listen for the load complete event for the URLLoader object
myURLLoader.addEventListener(Event.COMPLETE,weatherLoadComplete);

Now that the HTML file is in flash we can write a regexp to find specific data. Creating named groups within your regexp was new to me and an easy way to access specific data later on.

//Create a regexp literal that will pull out the just the air temperature from the web page
var weatherPattern:RegExp = /Temperature<BR>.*<strong>(?P<airtemp>.*)°C<\/strong>/;

The next step is to run that regexp against the text document. If a match is found you can access the whole string of the match or just the named group.

//Load complete event handler that traces out the regular expression data
function weatherLoadComplete(e:Event):void{
    //Execute the pattern against the text document returning an object containing a match
    var match:Object = weatherPattern.exec(e.target.data);
    //Since exec returns an object this will can use the full match
    trace(match);
    //Or just the group
    trace(match.airtemp);
}

Complete source.

//Create a request for the weather page
var myURLRequest:URLRequest = new URLRequest("http://www.weatheroffice.gc.ca/marine/marine_e.html?46146");
//Load the weather page into a urlloader object.
var myURLLoader:URLLoader = new URLLoader(myURLRequest);
//Listen for the load complete event for the URLLoader object
myURLLoader.addEventListener(Event.COMPLETE,weatherLoadComplete);
//Create a regexp literal that will pull out the just the air temperature from the web page
var weatherPattern:RegExp = /Temperature<BR>.*<strong>(?P<airtemp>.*)°C<\/strong>/;
//Load complete event handler that traces out the regular expression data
function weatherLoadComplete(e:Event):void{
    //Execute the pattern against the text document returning an object containing a match.
    var match:Object = weatherPattern.exec(e.target.data);
    //Since exec returns an object this will can use the full match
    trace(match);
    //Or just the group
    trace(match.airtemp);
}

Leave a Reply