« The Disappearing Spoon | Main | Jupiter's Travels »

Sanitize String for Regular Expression

I recently came across a need to use a user supplied input in a regular expression. To prevent any special characters in the user's string from being treated as a regular expression control character I stumbled upon this solution. Alas I can't remember where I found it but wanted to share.

/**
* Convert a random string into a format that will make sure it doesn't
* impact a regular expression when inserted into it.
* @param string String to sanitize.
* @return Sanitized string
*/
public function sanitizeForRegExp(string:String):String
{
    if (string == null)
    {
        return null;
    }
    return string.replace(new RegExp("([{}\(\)\^$&.\*\?\/\+\|\[\\\\]|\]|\-)","g"), "\\$1");
}

Tags: as3 flex regexp