正则表达式 - 字符串不应包含超过 7 位数字

Regex - String should not include more than 7 digits

字符串规则:


测试用例:

我如何想出相同的正则表达式?

我面临的问题是 - 如何保持整个字符串中的位数。数字可以出现在字符串中的任何位置。

我想要一个纯正则表达式解决方案

想通了!

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

每个数字字符都可以被非数字字符包围。

方法一

如果您愿意将一些逻辑放在 JavaScript 中,就像这个函数应该做的一样简单:

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

演示

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 />';

(另见 this Fiddle


方法二

如果您希望所有逻辑都在您的正则表达式中而不是您的 JavaScript,您可以使用像 /^(\D*\d?\D*){7}$//^([^0-9]*[0-9]?[^0-9]*){7}$/ 这样的正则表达式并使用 RegExp.prototype.test() instead of String.prototype.match()测试你的琴弦。

在这种情况下,您的验证函数将如下所示:

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

演示:

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 />';

以下正则表达式可以检查总位数是否小于 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>");
}