Using vars in regular expressions (AS3)

Here’s a quick tip that you can file under good to know.

I typically end up using regex’s at some point in most projects. Anything with user input is pretty much a guarantee. Recently when adding some new functionality to a strip tags util I came across a situation I’ve never encounter before in ActionScript. As the title suggests I wanted to use a variable value in the expression, while this isn’t typically an issue, I came a across a situation where it didn’t work. Here is the real world example.

Original regex1:


This nifty expression works like a charm. But I wanted to update it so the developer could limit which tags it stripped to those specified in a array. Pretty straight forward stuff, to use a variable value in a regex you first need to build it as a string and then convert it. Something like the following:

var exp:String = 'start-exp' + someVar + 'more-exp';
var regex:Regexp = new RegExp(exp);

Pretty straight forward. So when approaching this small upgrade, that’s what I did. Of course one big problem was pretty clear.

var exp:String = '/<' + tag + '("[^"]*"|'[^']*'|[^'">])*>/';

Guess what, invalid string! Better escape those quotes in the string. Whoops, that will break the regex! I was stumped. So I opened up the language reference to see what I could find. The source parameter, (which I’ve never used before,) caught my eye. It returns a String described as “the pattern portion of the regular expression.” It did the trick perfectly.

Here is the solution:

var start:Regexp = /])*>/ig;
var complete:RegExp = new RegExp(start.source + tag + end.source);

You can reduce it down to this for convenience:

var complete:RegExp = new RegExp(/])*>/.source + tag, 'ig');

Anyways, put that away into the old memory bank, it might come in handy.

1Original expression from Mastering Regular Expressions, by Jeffrey E.F. Friedl.


Flash, ActionScript-3, regex, regexp

You can contact me on Twitter.

Recent & Popular Articles

Browse All >