字符串规则:
测试案例:
abcd1234ghi567
⟶True
1234567abc
⟶true
ab1234cd567
⟶true
abc12
⟶True
abc12345678
⟶False
我如何为它提出正则表达式?
我面临的问题是 - 如何保持整个字符串中的数字位数。数字可以出现在字符串中的任何位置。
我想要一个纯正则表达式解决方案
答案 0 :(得分:6)
如果您可以将一些逻辑放在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()代替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 />';
答案 1 :(得分:3)
想通了!
/^(\D*\d?\D*){0,7}$/
每个数字字符都可以用非数字字符包围。
答案 2 :(得分:1)
以下正则表达式可以检查总位数是否小于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>");
}