简体   繁体   English

如何使用正则表达式限制位数但允许前面有零

[英]How to limit number of digits using regex but allow zeros in front

I want to limit the matches to 7 digits at most, but at the same time I want to allow zeroes in front of the number.我想将匹配限制为最多 7 位数字,但同时我想允许数字前面有零。 Right now it's allowing numbers such as 0, 1, 12, 123, 1234, 12345, 123456, 1234567 which is expected.现在它允许诸如 0、1、12、123、1234、12345、123456、1234567 之类的数字,这是预期的。 This is the problem, I also want to find a match for numbers such as 0001234567 but not 12345678. This is the regex I'm using:这就是问题所在,我还想找到匹配数字(例如 0001234567 但不是 12345678)的匹配项。这是我正在使用的正则表达式:

/^[1-9][0-9]{0,6}$|^0$/g

Try this /^0*[0-9]{7}$/试试这个/^0*[0-9]{7}$/

  • 0001234567 - pass 0001234567 - 通过
  • 1234567 - pass 1234567 - 通过
  • 12345678 - error 12345678 - 错误
  • 12345 - error 12345 - 错误

This should do it:这应该这样做:

/^0*[1-9][0-9]{0,6}$/

It allows any number of leading zeroes.它允许任意数量的前导零。

As you als want to match 0, you might also use an alternation to match 1+ more zeroes as well由于您也想匹配 0,您也可以使用交替来匹配 1+ 个以上的零

^(?:0*[1-9]\d{0,6}|0+)$

Regex demo正则表达式演示

You might also use parseInt and check for the string length您也可以使用 parseInt 并检查字符串长度

 const limitNumbers = s => parseInt(s, 10).toString().length < 8; const strings = [ "0", "1", "12", "123", "1234", "12345", "123456", "1234567", "0001234567", "12345678", ]; strings.forEach(s => console.log(`${s}: ${limitNumbers(s)}`))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM