1

I have a really complex JavaScript replace regex function and I am wondering is there a way to format the regex code on multiple lines like this:

/
(
    ([0-9]{1,2})
    (\/|\.)
    ([0-9]{1,2})
    (\/|\.)
    ([0-9]{2,4})\s
)?
([0-9]{1,2})
:
([0-9]{1,2})
(
    (:|\s)
    ([0-9]{1,2})
)?
/ig

Also I'd like to ask if there is another way to format regex so it's easier to read.

Ivan Dokov
  • 4,013
  • 6
  • 24
  • 36
  • 1
    Regex is pretty much write-only. The best solution might be to put that along with explanations in a comment above the actual regex. – JJJ May 03 '13 at 16:15

2 Answers2

3

JavaScript doesn't have support for the /x flag (which allows spaces and comments), but you can split your expression over multiple lines using strings. For example:

var re = new RegExp(
     "foo" +
     "bar" +
     "baz",
     "ig");

Of course this has the disadvantage of regular string quoting of regex (double escapes).

You could also use XRegExp with its (?x) flag, but you are still limited by the regular JS string quoting.

Qtax
  • 33,241
  • 9
  • 83
  • 121
1
myPatter = new RegExp(
     '([0-9]{1,2})'   +
     '.... a new line' +
     '... anotherline'
);
Megacier
  • 394
  • 4
  • 9
Griffin
  • 13,184
  • 4
  • 29
  • 43
  • @IvanDokov Qtax had a better idea, I stupidly made it too complex with the array and join! (late in the day here) – Griffin May 03 '13 at 16:21