开发者

Regular expression in Java for positive integers (excluding those starting with zero)

I currently use "(\d){1,9}", but it fail开发者_运维知识库s to invalidate numbers such as "0134". The expression must only validate numbers that are positive INTEGERS. Thanks.


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}.

By the way: 0134 is a positive integer. 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. Copy that code and change the part with the 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜