AS3 Handy Snippets: Handy Regular Expressions

Hey everyone. This week, I’m bringing you some handy regular expression snippets I use quite frequently. If you are unfamiliar with regular expressions, think of them as a different language that you use within ActionScript. I’m not going to go into detail about Regular Expressions, there’s far better documentation on the Adobe LiveDocs here for the object & here for regular expression syntax.

Anyway, here are some handy regular expressions:

Email Validation:

var eMail:RegExp = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);

I didn’t write this one myself, although it’s probably the one I use the most. This is the best email validation out there that I’ve seen out there -some forget about us in the UK with our .co.uk domains!

Word Count:

var wCount:RegExp = new RegExp(/[ ]?[a-zA-Z0-9"-'@~#!£\$%\^&\*]+[ ]?/gi);

I wrote this one after doing a lot of reading in the LiveDocs. Basically, it finds all words in a string. Simple.

Telephone Number:

var telNumber:RegExp = new RegExp(/^[0-9]{5}[ ]?[0-9]{3}[ ]?[0-9]{3}$/);

This expression validates telephone numbers. From time to time, you’ll get users who will input them in different ways (using spaces and whatnot). This validates the number in these situations without any problems.

Here is a small Flash demo displaying them in action:

Download it HERE.

Stay cool,

-Bill

Tags: , , , ,