Mr. Ed Mr. Ed - 4 months ago 19
Android Question

Regex allow dot and comma

I have this expression

^(?!0*(\.0+)?$)(\d+|\d*\.\d+)$


and it works fine except that I would like it to except a comma as a separator as well. With this pattern, 1,5 or ,123 is false. It should be true.

Specifically,

0 = false

0.0 = false

null = false

. = false

, = false

0.123 = true

0,123 = true

.123 = true

,123 = true

123.123 = true

123,123 = true

Answer

I think you are looking for

^(?!0*[.,]?0+$)\d*[.,]?\d+$

See the regex demo

Pattern details:

  • ^ - start of string
  • (?!0*[.,]?0+$) - a negative lookahead that will fail the match if the whole string is equal to 0+ zeros followed with 1 or 0 commas or dots and followed with one or more zeros (if the value is 0000, 0, 0,000, or .000, or ,000, etc.)
  • \d* - zero or more digits
  • [.,]? - an optional comma or dot
  • \d+ - 1 or more digits
  • $ - end of string.

Remember that you do not need ^ and $ when using the pattern with the String#matches method, but it is a good idea to keep them explicit in the pattern for better readability and further testing.