Robin Rodricks
Robin Rodricks

Reputation: 114016

AS3 - How to properly escape regex

I've got a couple of regex's in AS3 that are defined with the inline AS3 regex syntax like:

I want to convert that to the AS3 RegEx class constructor like:

I'm not sure if I have to escape the backslashes or not. Do you know how to convert it?


    /**  ------------------------- Regular Expressions ---------------------------- */

    public static var multiLineCComments:RegExp     = /\/\*[\s\S]*?\*\//gm;
    public static var singleLineCComments:RegExp        = /\/\/.*$/gm;
    public static var singleLinePerlComments:RegExp = /#.*$/gm;
    public static var doubleQuotedString:RegExp     = /"([^\\"\n]|\\.)*"/g;
    public static var singleQuotedString:RegExp     = /'([^\\'\n]|\\.)*'/g;
    public static var multiLineDoubleQuotedString:XRegExp   = new XRegExp('"([^\\\\"]|\\\\.)*"', 'gs');
    public static var multiLineSingleQuotedString:XRegExp   = new XRegExp("'([^\\\\']|\\\\.)*'", 'gs');
    public static var xmlComments:RegExp                = /(&lt;|<)!--[\s\S]*?--(&gt;|>)/gm;
    public static var url:RegExp                        = /\w+:\/\/[\w-.\/?%&=:@;]*/g;

Upvotes: 2

Views: 808

Answers (2)

Robin Rodricks
Robin Rodricks

Reputation: 114016

I understood how to do it.

  1. Delete the first and last / which is the part of the AS3 regex syntax.

  2. Place the ending options such as g or gm in the 2nd argument.

  3. And lastly escape every backslash (\) by replacing it with 2 backslashes

So in summary:

  • Inline syntax : /\/\*[\s\S]*?\*\//gm
  • RegExp syntax : new RegExp ("\\/\\*[\\s\\S]*?\\*\\/", 'gm')

Upvotes: 1

Kodiak
Kodiak

Reputation: 5978

You could do this another way:

private static const pattern:RegExp = /\/\*[\s\S]*?\*\//;
public static var regex:XRegExp = new XRegExp(pattern.source, "gm");

Upvotes: 0

Related Questions