AS3 RegExp Basics
Hi all. The idea behind this site is not really tutorials and stuff, but just be my repository of useful stuff that i create/find/improve. But i want to take this post and talk about Regular Expressions. Something that other programmers are very familiar with, but it’s kind of a new thing on actionscript. Recently i had to remove all html tags from a text before showing on my application. At first it seems like an easy task, but it’s not. It took me like 2 hours to get this script working:
public static function remove(base, piece:String):String
{
var res:String = base;
while(res.indexOf(piece)!=-1){
res = res.substr(0,res.indexOf(piece))+ res.substr(res.indexOf(piece) + piece.length);
}
return res;
}
public static function removeHTMLTags(str:String):String{
var start:int = str.indexOf("<");
var end:int = str.indexOf(">")+1;
if(start != -1 && end != -1){
var aux:String = remove(str,str.substring(start,end));
return extractText(aux);
}
return str;
}
As you can see i use a recursive function to remove parts of the text and when there’s no more tags to remove, i return the value. You can use Like this
var texto:String = "Some Text"; trace(StringUtils.extractText(texto)); // output: Some TextAt first glance, this works perfectly, but when you have a long text, the recursive function takes a lot of time to process and in some cases will crash the Flash Player. That’s because the loop runs along all the text, even the parts where there’s no html tags to be removed. That’s where the Regular Expressions come handy. You don’t have to use loops to change familiar or standardized portions of the text. With Regular Expressions, those areas are scanned on a low level basis, providing a much more effective solution. Here is the same code, using Regular Expressions:
public static function removeHTMLTags(text:String):String
{
return text.replace(/<\/?[^>]+>/igm, '');
}
Another thing that makes Regular Expressions very handy is on form validation. For instance, let’s take a look on this standard mail validation script:
private function mailValidation( text :String ) :Boolean
{
var pos :int = text.indexOf("@");
var p :int = text.indexOf(".", pos );
if ( pos = 1 && p < (pos+2) ) ) return false;
return true;
}
Looks good enough, but you notice there’s a lot of returns and it’s not a very elegant script. Check out how you can do it with Regular Expressions:
public static function validateEmail(email:String):Boolean
{
return Boolean(email.match(/^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i;);
}
Se, a lot more elegant. Now, the dude from this site, wrote a preety good as2 class for Regular Expressions Validations. It’s a really cool class you can store your regExp on a xml file and provide a error description to it. I’m translating it to as3 and will post here as soon as i’m finished. Also, please check out Adobe’s as3 regExp documentation here.