Regular Expressions in Flex and AS3

I’ve needed to user Regular Expressions a couple of times since they were introduced in ActionScript 3 and invariably find myself trawling the Regular Expression tutorial/example websites out there which in general I find very confusing! I don’t think Regular Expressions are that difficult to grasp (the basic anyway) but none of the example sites I’ve found have clear explanations of the syntax.

I’m currently developing a Crossword Application in Flex for a client which is pretty much complete. However, one of the bugs I had to resolve today was being caused by some unforseen incompatibility issues with the solution text node coming from the client’s huge database of crosswords xml files. If a solution for example had a space, apostrophe, hypen or various other punctionation it needed to be stripped out of the node by my code to ensure that the correct number of cells were generated on my crossword app grid. So here’s an example of using a regular expression to do just that:

var notCharOrNum:RegExp = /[^A-Za-z0-9]/gi;
var myText:String = "The bee’s knees";
myText = myText.replace(notCharOrNum,""); //outputs “Thebeesknees”
trace(myText);

In summary the reg expression means match everything that isn’t either a letter or a number. The ^ bit is the special character than means except these characters. The g means global – I think that just means the match continues searching throughout the string until it reaches the end. The i means case insensitive search so I guess this would do the same thing:

var notCharOrNum:RegExp = /[^a-z0-9]/gi;
var myText:String = "The bee’s knees";
myText = myText.replace(notCharOrNum,""); //outputs “Thebeesknees”
trace(myText);

Yep – just checked and it does!