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

sup*_*kar -4 regex regex-negation

字符串规则:

  • 可以包含0-7位数字

测试用例 :

  • abcd1234ghi567True
  • 1234567abctrue
  • ab1234cd567true
  • abc12True
  • abc12345678False

我如何为它提出正则表达式?

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

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

Joh*_*ers 6

方法1

如果您可以将一些逻辑放在JavaScript中,那么像这个函数一样简单:

function validate(teststring) {
    return teststring.match(/\d/g).length < 8;
}
Run Code Online (Sandbox Code Playgroud)

演示

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 />';
Run Code Online (Sandbox Code Playgroud)

(另见小提琴)


方法2

如果您希望将所有逻辑都放在正则表达式而不是JavaScript中,则可以使用类似的正则表达式/^(\D*\d?\D*){7}$/,/^([^0-9]*[0-9]?[^0-9]*){7}$/并使用RegExp.prototype.test()而不是String.prototype.match()来测试字符串.

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

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

演示:

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 />';
Run Code Online (Sandbox Code Playgroud)