luca_bruegger
luca_bruegger

Reputation: 57

Regex that should match 0-999, 0.0-999.9 as well as 0,0-999,9

I am once again struggling with regex. I need a regex which matches only numbers from 0-999 or numbers from 0-999 with one decimal, eg. 0.0-999.9.

The Regex I made /^([1-9][0-9]{0,2})|([1-9][0-9]{0,2})[,.][0-9]$/ has the error that it matches also 1. instead of 1.5, that shouldn't be the case.

Further examples:

1 -> Match (in range 0-999)
1. -> No Match (no decimal)
1, -> Again no Match (no decimal)
1,5 -> Matches (in range 0,0-999,9)
1324 -> does not Match (over 999,9)
15.5 -> Matches (in range 0.0-999.9)
999,9 -> Matches (max. reached)

Thanks in advance for your Help.

Upvotes: 1

Views: 584

Answers (2)

Robert McKee
Robert McKee

Reputation: 21487

^(?:[1-9]\d{1,2}|\d)(?:[.,]\d)?$ should work.

Demo: https://regex101.com/r/vsL89V/3

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163287

To match from 0 - 999 with an optional part to match either a . or a ,, you could use

^\d{1,3}(?:[.,]\d)?$

regex demo

Upvotes: 1

Related Questions