1

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);
6
  • As I mentioned, remove all spaces. regex101.com/r/kNHkMn/2 Commented Feb 6, 2017 at 23:13
  • @WiktorStribiżew I did but it still tests true for both "123456" and "135468". Commented Feb 6, 2017 at 23:20
  • 123456 does not match, and 135468 looks valid as per the regex. Same results are obtained at regexstorm.net/tester Commented Feb 6, 2017 at 23:22
  • @WiktorStribiżew Apparently I needed to double the back-slashes as they were evaluated as escape characters. Commented Feb 6, 2017 at 23:32
  • Why not just use a function that process the string letter by letter? Commented Feb 6, 2017 at 23:33

1 Answer 1

1

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$)/;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.