Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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.

like image 779
skyork Avatar asked Dec 17 '22 14:12

skyork


1 Answers

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.

like image 91
Roland Illig Avatar answered Apr 19 '23 23:04

Roland Illig