John L. John L. - 4 years ago 179
Javascript Question

Corresponding Regexp In Javascript

I have the following regexp which should detect sequential digits like "123456" or "654321"in c# but cannnot convert it to the corresponding javascript regexp string.

string re = @"(?x)
^
# fail if...
(?!
# sequential ascending
(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){5} \d $
|
# sequential descending
(?:1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5} \d $
)
";


I tried the following Javascript but it seems to always return true:

var re = new RegExp("^(?!(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){5} \d $|(?:1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5} \d $)");
var isMatch = re.test(str);

Answer Source

Since the JavaScript regex engine does not support freespace (verbose) regex mode (enabled with the (?x) inline modifier) you need to remove all the formatting whitespace from the pattern.

In JS, you'd better use a regex literal notation to avoid the trouble of choosing the right number of backslashes to escape special regex metacharacters:

var re = /^(?!(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){5}\d$|(?:1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5}\d$)/;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download