Friday, February 10, 2012

AS3: Playing with Regular Expressions

How useful can Regular Expressions be? This is a question I have been continuously asking myself. Hence I have done up a simple demo of Regular Expression and you can easily identify how much time it can actually save you.

Let's take a look at the source code first.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute"
    creationComplete="creationCompleteEvent(event)">
 <mx:Script>
  <![CDATA[
   import mx.events.FlexEvent;
   
   //Dummy text for testing
   [Bindable]
   private var testStr:String = "info@info.com " +
    "apple@apple.com bestkirdape@gmail.com " +
    "best_kird_ape@gmail.com The above are " +
    "dummy email address.";
   //Regular Expression for checking email address
   private var emailRegExp:RegExp = /\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/gi;
   
   //The pattern you want the text that was found by the
   //Regular Expression to change into.
   private var pattern:String = "<a href='event:mailto:$&'>$&</a>";
   
   //Click Handler for button
   protected function clickHandler(e:MouseEvent):void
   {
    lblResult.htmlText = String(lblInput.text).
     replace(emailRegExp,pattern); 
   }
   
   //Upon clicking on the link in the validated result,
   //open up the email address.
   protected function linkHandler(e:TextEvent):void
   {
    navigateToURL(new URLRequest(e.text),"_self");
   }
   
   //Once the view have been created validate the Dummy text
   //using the Regular Expression and display the result.
   protected function creationCompleteEvent(e:FlexEvent):void
   {
    btnChange.dispatchEvent(
     new MouseEvent(MouseEvent.CLICK));
   }
  ]]>
 </mx:Script>
 
 <mx:VBox width="100%" 
    height="100%"
    paddingLeft="50"
    paddingRight="50"
    paddingBottom="50"
    paddingTop="50"
    verticalAlign="middle"
    horizontalAlign="center">
  <mx:TextInput id="lblInput"
       width="100%"
       height="20%"
       text="{testStr}"/>
  <mx:Button id="btnChange" 
       label="Change Text Now..."
       click="clickHandler(event)"/>
  <mx:TextArea id="lblResult"
      width="100%"
      height="20%"
      link="linkHandler(event)"/>
 </mx:VBox>
</mx:Application>
Although the source codes might look pretty short but it's actually something that was pretty useful.

The user will enter some text into the text field and upon clicking on the button, the program will automatically change all the text into clickable urls. Isn't that great? This have definitely shorten the amount of time required to write out individual functions to create the same effect.

* Click here to view the demo of this example.
^ Click here for the source files of this demo.

~ Click here for one of the best guide to get your way around Regular Expressions.

No comments:

Post a Comment