Reputation: 4929
I'm trying to figure out a regex expression that does the following. Both conditions below must be true: 1) Between 0 and 100 inclusive 2) Can contain one or two decimals only but not obligatory.
It should not allow 100.01 or 100.1 100 is the maximum value, or 100.0 or 100.00
I tried ^(100(?:\.00)?|0(?:\.\d\d)?|\d?\d(?:\.\d\d)?)$
which helped me in this question
but this does not accept 99.0
(one decimal).
I'm probably very close.
Upvotes: 2
Views: 5324
Reputation: 626845
You just need to make each second decimal digit optional:
^(?:100(?:\.00?)?|\d?\d(?:\.\d\d?)?)$
^ ^
See the updated regex demo. The 0(?:\.\d\d)?
alternative is covered by \d?\d(?:\.\d\d)?
one (as per Sebastian's comment) and can thus be removed.
The ?
quantifier matches one or zero occurrences of the subpattern it quantifies.
Pattern details:
^
- start of string(?:
- start of an alternation group:
100(?:\.00?)?
- 100
, 100.0
or 100.00
(the .00
is optional and the last 0
is optional, too)\d?\d(?:\.\d\d?)?
- an optional digit followed by an obligatory digit followed with an optional sequence of a dot, a digit and an optional digit.)
- end of the alternation group$
- end of string.BONUS: If the number can have either .
(dot) or ,
(comma) as a decimal separator, you can replace all \.
patterns in the regex with [.,]
:
^(?:100(?:[.,]00?)?|\d?\d(?:[.,]\d\d?)?)$
Upvotes: 3