Java regex for positive integers (except those starting with zero)

I am currently using "(\ d) {1.9}", but it cannot invalidate numbers such as "0134". An expression should only check numbers that are positive INTEGERS. Thank.

+3
source share
2 answers

You are using an expression right now [0-9]{1,9}, so this explicitly allows the number 0134. If you want the first character not to be zero, you should use [1-9][0-9]{0,8}.

By the way: 0134 is a positive integer. This is an integer, and it is positive .;)

edit:

To prevent integer overflows, 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}
  • ...

, . |, .

, Integer.valueOf(String), . NumberFormatException.

+6

, :

^(?!^0)\d{1,9}$

, , .

+5

All Articles