javaregex

Pattern Matcher valid number java


I want to have a number validation. Rules are:

  1. A number can start with + or - or nothing (it is taken as a positive number)
  2. Cannot start with 0
  3. Can have a fraction either . or ,
  4. Cannot end with 0

So acceptable numbers are: +123, -123, 123, 1023, 123.03, 123,03. Non acceptable numbers are: 001, 1.000, any letters

I give you the expression that I ve built so far, on Dan's Tools. I have managed almost everything, except expressions after the the fraction. Every help is acceptable.

Expression: (^(\+|-?)([1-9]+))([0-9]+)(\.|,?)

Thanks in advance Nikos


Solution

  • Except the fractional part that is missing in your pattern, your regex won't match single digit numbers as you quantified [1-9] and [0-9] with + quantifier requiring at least one char.

    You can use

    ^[+-]?[1-9][0-9]*(?:[.,][0-9]*[1-9])?$
    

    See the regex demo and the regex graph:

    enter image description here

    Details