Reputation: 13
Is it possible to write an regular expression which checks if a given digit occurs x amount of times?
I am trying to use the following code to determine if in a given string (of 16 digits), there are at least more than one digits apparent. For example if there is only one digit 16 times, then there cannot be two different digits.
let multipleDigits = /[0-9]{16}/g.test(ccString);
console.log('More than one digit? ' + result);
The whole function is:
function validator(ccNumber) {
let ccString = ccNumber.toString();
The call and output is:
validator(1111111111111112);
More than one digit? false
Expected output is 'true'. I would appreciate any help / guidance.
Thank you
p.s. Another variation of the regex I'm trying is:
let testOnlyOneDigit = /\d{16}/g;
Upvotes: 1
Views: 101
Reputation: 370689
Test for if the string contains only a single digit by capturing \d
at the beginning, and backreferencing that capture group until reaching the end of the string. Then negate that test to see if the string contains any other digits:
const hasMoreThanOneDigit = num => !/^(\d)\1*$/.test(num.toString());
console.log(hasMoreThanOneDigit(1111111111111112));
console.log(hasMoreThanOneDigit(1111111111111));
If you can't count on the input being a number, and you need to validate that as well ("a numeric string which contains at least two different digits"), then the test will have to be a bit more complicated: match and capture a digit, then match more digits, and eventually match one which is not the same as the captured digit by putting negative lookahead before it:
const hasMoreThanOneDigit = num => /^(\d)\d*(?!\1)\d+$/.test(num.toString());
console.log(hasMoreThanOneDigit(1111111111111112));
console.log(hasMoreThanOneDigit(1111111111111));
console.log(hasMoreThanOneDigit('111111AAA1111111'));
Upvotes: 1
Reputation: 271050
We can construct a regex to test for whether the number has only one unique digit, and then invert that result and print it.
The regex is:
/^(\d)\1{15}$/
It captures the first digit into group 1, and then checks if whatever is in group 1 repeats for 15 more times.
Then we can invert the result with !
:
function validator(ccNumber) {
let ccString = ccNumber.toString();
let multipleDigits =/^(\d)\1{15}$/.test(ccString);
console.log('More than one digit? ' + !multipleDigits);
}
validator(1111111111111111);
validator(1111111111111112);
Upvotes: 1