I have a C# code that check's for falseNumber on regex basis:
public bool falseNumber(string num)
{
try
{
num = num.Replace("-", "");
string re = @"(?x)
^
# fail if...
(?!
# repeating numbers
(\d) \1 $
|
# sequential ascending
(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5} \d $
|
# sequential descending
(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5} \d $
)
# match any other combinations of 6 digits
\d
$
";
return Regex.IsMatch(num, re);
}
catch (Exception y) { return true; }
}
I need this code to be converted to JS, so I have written:
const falseNumber = (num) =>
{
num = num.replaceAll("-", "");
let re = /(?x)^(?!(\d)\1 $|(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5}\d$|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5}\d$)\d $/
return re.test(num);
}
But that gives me error:
VM46:5 Uncaught SyntaxError: Invalid regular expression: /((?x)^(?!(\d) \1 $|(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5} \d $|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5} \d $)\d $)/: Invalid group at falseNumber (:5:12) at :1:1
Any help would be highly appreciated.
Thank you.
const falseNumber = (num) =>
{
num = num.replaceAll("-", "");
let re = /(?x)^(?!(\d)\1 $|(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5}\d$|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5}\d$)\d $/
return re.test(num);
}
console.log(falseNumber('33-3333333-33'));
CodePudding user response:
x
modifier is not built in JS that's why you get an error. And in your case, you don't need to use x
modifier because you don't use comments or have any whitespace in your regex expression in JS.
x
modifier definition:
This flag tells the engine to ignore all whitespace and allow for comments in the regex; also called verbose. Comments are indicated by a starting "#"-character. If you need to include a space character in your regex, it must now be escaped '\ '.
const falseNumber = (num) =>
{
num = num.replaceAll("-", "");
let re = /^(?!(\d)\1 $|(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5}\d$|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5}\d$)\d $/
return re.test(num);
}
console.log(falseNumber('33-3333333-33'));