简体   繁体   English

正则表达式允许带前导零的数字

[英]Regex that allow for numbers with leading zeros

My requirement is that I should pass 4 or more "digits" and fail the rest. 我的要求是我应该通过4个或更多的“数字”,而其余部分不通过。 The regex I used is: 我使用的正则表达式是:

var test = new RegExp(/[0-9]{4,100}$/);

However, numbers with leading zeros like 0001 or 0123 fail. 但是,带有前导零的数字(例如0001或0123)会失败。 How can I modify the regex to allow for numbers with leading zeros while sticking to my requirement. 如何在符合我的要求的同时修改正则表达式以允许前导零的数字。 Thanks! 谢谢!

Make sure you have quotes around the number you're testing. 确保您要测试的数字周围有引号。 The syntax is: 语法为:

RegExpObject.test(string)

var test = new RegExp(/[0-9]{4,100}$/); var test = new RegExp(/ [0-9] {4,100} $ /);

This returns false because it is interpreted as the number 9: 这将返回false,因为它被解释为数字9:

test.test(000009);

The leading zeros are ignored. 前导零被忽略。

This returns true because the whole string is considered: 这将返回true,因为考虑了整个字符串:

test.test('000009');

Use the follwoing regex to find numbers that do not start with zeros: 使用以下正则表达式查找不以零开头的数字:

\b[1-9]\d{3,}

DEMO 演示

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

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