Javascript 匹配最多 9 位整数的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6229906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular expression to match integers up to 9 digits
提问by t0mcat
I want to create a regular expression where only numbers are allowed with max length 9 and no minimum length. I came up with \d{9}[0-9]
but it isn't working.
我想创建一个正则表达式,其中只允许最大长度为 9 且没有最小长度的数字。我想出来了,\d{9}[0-9]
但没有用。
回答by vcsjones
You're close. Try this:
你很接近。尝试这个:
^\d{0,9}$
The ^ and $ match the beginning and the end of the text, respectively. \d{0,9}
matches anywhere in the string, so d0000
would pass because it would match the 0000
even though there is a d in it, which I don't think you want. That's why they ^$ should be in there.
^ 和 $ 分别匹配文本的开头和结尾。\d{0,9}
匹配字符串中的任何位置,所以d0000
会通过,因为0000
即使其中有广告,它也会匹配,我认为您不想要。这就是为什么他们 ^$ 应该在那里。
回答by NT3RP
Regular expressions can be tricky; what you've written does the following:
正则表达式可能很棘手;你写的内容如下:
\d
- digit\d{9}
- exactly 9 digits\d{9}[0-9]
- exactly 9 digits, followed by something between 0 and 9
\d
- 数字\d{9}
- 正好 9 位\d{9}[0-9]
- 正好是 9 位数字,后跟 0 到 9 之间的数字
If you want no minimum limit of length, but a maximum length of 9, you probably want the following regular expression:
如果您不需要最小长度限制,但最大长度为 9,您可能需要以下正则表达式:
\d{0,9}
- 0 to 9 digits
\d{0,9}
- 0 到 9 位数字
回答by Jan
I think It should be 1to 9 digits:
我认为它应该是1到 9 位数字:
^\d{1,9}$
回答by Brian Fisher
It looks like you were close, try \d{0,9}
.
看起来你很接近,试试吧\d{0,9}
。