[英]Regular expression in Java for positive integers (excluding those starting with zero)
I currently use "(\\d){1,9}", but it fails to invalidate numbers such as "0134". 我目前使用“(\\ d){1,9}”,但它无法使诸如“0134”之类的数字无效。 The expression must only validate numbers that are positive INTEGERS. 该表达式必须仅验证积极INTEGERS的数字。 Thanks. 谢谢。
Right now you use the expression [0-9]{1,9}
, so this clearly allows the number 0134
. 现在你使用表达式[0-9]{1,9}
,所以这显然允许数字0134
。 When you want to require that the first character is not a zero, you have to use [1-9][0-9]{0,8}
. 如果要求第一个字符不为零,则必须使用[1-9][0-9]{0,8}
。
By the way: 0134 is a positive integer. 顺便说一下:0134 是一个正整数。 It is an integer number, and it is positive. 它是一个整数,是正数。 ;) ;)
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}
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. 或者,查看Integer.valueOf(String)
方法,它如何解析数字并检查溢出。 Copy that code and change the part with the NumberFormatException
. 复制该代码并使用NumberFormatException
更改该部件。
You can use a regex like below: 你可以使用如下的正则表达式:
^(?!^0)\d{1,9}$
What you mean to say is positive integers without leading zeroes I believe. 你的意思是说我认为没有前导零的正整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.