简体   繁体   English

正则表达式精确匹配 6 位数字,数字之间有任意数量的空格

[英]Regex to match exactly 6 digits with any number of spaces between the digits

I recently needed to create a regular expression for OTP values in JavaScript.我最近需要为 JavaScript 中的 OTP 值创建一个正则表达式。 The input should contain 6 digits with spaces any where in between.输入应包含 6 位数字,中间有空格。 I am not regex-savvy at all and even though I tried looking for a better way, I ended up with this:我根本不精通正则表达式,即使我尝试寻找更好的方法,我最终还是这样:

/^[\d ]*$/

With this I can have spaces with digits but here I don't have control over the number of digits.有了这个,我可以有数字空格,但在这里我无法控制数字的数量。

Try this:尝试这个:

 let OTPs = [ "123456", "12345", // Invalid "1 2345 6", "1 2 3 4 5 6", "1 2 3 4 5 6", "a 2 b 4 5 6" // Invalid ] let validOTPs = OTPs.filter(otp => otp.match(/^(\d\s*){6}$/g)) console.log(validOTPs)

You also try below regex.你也试试下面的正则表达式。 See it working at https://regex101.com/r/6rGjOU/1请参阅https://regex101.com/r/6rGjOU/1

^(\d(\s+)?){6}$

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

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