Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include an inline comment in a regular expression in JavaScript [duplicate]

Inline comments works when a string passed to the RegExp constructor:

RegExp("foo"/*bar*/).test("foo")

but not with an expression. Is there any equivalent or alternative in JavaScript to emulate x-mode for the RegExp object?

like image 531
Paul Sweatte Avatar asked Nov 16 '12 20:11

Paul Sweatte


2 Answers

Javascript supports neither the x modifier, nor inline comments (?#comment). See here.

I guess, the best you can do, is to use the RegExp constructor and write every line in e separate string and concatenate them (with comments between the strings):

RegExp(
    "foo" + // match a foo
    "bar" + // followed by a bar
    "$"     // at the end of the string
).test("somefoobar");
like image 81
Martin Ender Avatar answered Sep 19 '22 06:09

Martin Ender


Other than using a zero-length sub-expression, it's not possible. Examples of "comments":

/[a-z](?!<-- Any letter)/

(?!..) is a negated look-ahead. It matches if the previous is not followed by the string within the parentheses. Since the thing between (?! and ) is a real regular (sub)expression, you cannot use arbitrary characters unless escaped with a backslash

An alternative is to use the positive look-ahead:

/[a-z](?=|<-- Any letter)/

This look-ahead will always match, because obviously the a-z is also followed by an empty string.

like image 35
Rob W Avatar answered Sep 21 '22 06:09

Rob W