I want a regex which matches 10 digit alternating numbers like 1212121212
3434343434
so on. I know this is not right way to ask here. But I tried a lot from my side I was not able to figure out so reaching out for help.
It cannot be 1313131313. I should be the next number.
CodePudding user response:
If the string is always 10 characters long and we always have single-digit numbers then simply take the first two characters, repeat 5 times and compare:
const check = str => {
const a = str[0];
const b = str[1];
return a 1 === b && `${a}${b}`.repeat(5) === str;
};
check('1212121212');
//=> true
check('1212121215');
//=> false
check('1313131313');
//=> false
CodePudding user response:
If the repetition is always two figures you can do something like (\d\d)\1{4}
.
This is create a group with two digits (\d\d)
, find the same match as previous four times in a row \1{4}
.
CodePudding user response:
You might also use Array.from and specify a length and an offset to get the alternation for the next number:
const alternating = (len, offset) =>
Array.from({ length: len }, (_, index) => (index % 2) offset).join('');
console.log(alternating(10, 1) === "1212121212");
console.log(alternating(10, 3) === "3434343434");
console.log(alternating(10, 2) === "1313131313");
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
For pure regex you would just have to work out the different combinations because regex doesn't support the concept of numbers nor their sequence; everything is a string of chars.
^(01|12|23|34|45|56|67|78|89)\1{4}$
If 9090909090
is valid then:
^(01|12|23|34|45|56|67|78|89|90)\1{4}$