'Regex - String should not include more than 7 digits

Rules for String:

  • Can contain 0-7 digits

Test Cases :

  • abcd1234ghi567True
  • 1234567abctrue
  • ab1234cd567true
  • abc12True
  • abc12345678False

How do I come up with a regular expression for the same?

The problem I am facing is - How to keep the count of digits in the whole string. The digits can occur any where in the string.

I would like a Pure regex solution



Solution 1:[1]

figured it out!

/^(\D*\d?\D*){0,7}$/

Every numeric char can be surrounded by non-numeric chars.

Solution 2:[2]

Approach 1

If you're OK with putting some of your logic in your JavaScript, something as simple as this function should do :

function validate(teststring) {
    return teststring.match(/\d/g).length < 8;
}

Demo

function validate(teststring) {
    return teststring.match(/\d/g).length < 8;
}

document.body.innerHTML =
    '<b>abcd1234ghi567 :</b> ' + validate('abcd1234ghi567') + '<br />' +
    '<b>1234567abc :</b> ' + validate('1234567abc') + '<br />'+
    '<b>ab1234cd567 :</b> ' + validate('ab1234cd567') + '<br />'+
    '<b>abc12 :</b> ' + validate('abc12') + '<br />'+
    '<b>abc12345678 :</b> ' + validate('abc12345678') + '<br />';

(see also this Fiddle)


Approach 2

If you prefer all of your logic to be in your regex instead of your JavaScript, you could use a regex like /^(\D*\d?\D*){7}$/ or /^([^0-9]*[0-9]?[^0-9]*){7}$/ and use RegExp.prototype.test() instead of String.prototype.match() to test your strings.

In that case, your validate function would look something like this :

function validate(teststring) {
    return /^([^0-9]*[0-9]?[^0-9]*){7}$/.test(teststring);
}

Demo :

function validate(teststring) {
    return /^([^0-9]*[0-9]?[^0-9]*){7}$/.test(teststring);
}

document.body.innerHTML =
    '<b>abcd1234ghi567 :</b> ' + validate('abcd1234ghi567') + '<br />' +
    '<b>1234567abc :</b> ' + validate('1234567abc') + '<br />'+
    '<b>ab1234cd567 :</b> ' + validate('ab1234cd567') + '<br />'+
    '<b>abc12 :</b> ' + validate('abc12') + '<br />'+
    '<b>abc12345678 :</b> ' + validate('abc12345678') + '<br />';

Solution 3:[3]

The following regex can check if the total digits are less than 7:

var i, strings = ["abcd1234ghi567", "1234567abc", "ab1234cd567", "abc12", "abc12345678"];
for (i of strings) {
  document.write(i + " -> " + /^(?:[\D]*[0-9][\D]*){0,7}$/.test(i) + "</br>");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Quinn