Java 中正整数的正则表达式(不包括以零开头的那些)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5998247/
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 in Java for positive integers (excluding those starting with zero)
提问by skyork
I currently use "(\d){1,9}", but it fails to invalidate numbers such as "0134". The expression must only validate numbers that are positive INTEGERS. Thanks.
我目前使用“(\d){1,9}”,但它无法使诸如“0134”之类的数字无效。该表达式必须仅验证正整数的数字。谢谢。
回答by Roland Illig
Right now you use the expression [0-9]{1,9}
, so this clearly allows the number 0134
. When you want to require that the first character is not a zero, you have to use [1-9][0-9]{0,8}
.
现在您使用表达式[0-9]{1,9}
,所以这显然允许数字0134
。当您想要求第一个字符不是零时,您必须使用[1-9][0-9]{0,8}
.
By the way: 0134 isa positive integer. It is an integer number, and it is positive. ;)
顺便说一句:0134是一个正整数。它是一个整数,并且是正数。;)
edit:
编辑:
To prevent integer overflow you can use this pattern:
为了防止整数溢出,您可以使用以下模式:
[1-9][0-9]{0,8}
[1-1][0-9]{9}
[2-2][0-1][0-9]{8}
[2-2][1-1][0-3][0-9]{7}
[2-2][1-1][4-4][0-6][0-9]{6}
- …
[1-9][0-9]{0,8}
[1-1][0-9]{9}
[2-2][0-1][0-9]{8}
[2-2][1-1][0-3][0-9]{7}
[2-2][1-1][4-4][0-6][0-9]{6}
- …
I think you get the idea. Then you combine these expressions with |
, and you are done.
我想你应该已经明白了。然后将这些表达式与 组合在一起|
,就大功告成了。
Alternatively, have a look at the Integer.valueOf(String)
method, how it parses numbers and checks for overflow. Copy that code and change the part with the NumberFormatException
.
或者,看看该Integer.valueOf(String)
方法,它如何解析数字并检查溢出。复制该代码并使用NumberFormatException
.
回答by manojlds
You can use a regex like below:
您可以使用如下正则表达式:
^(?!^0)\d{1,9}$
What you mean to say is positive integers without leading zeroesI believe.
你的意思是我相信没有前导零的正整数。