In my filter used into EditText, I want to be sure the user can only set .5 or .0 for decimal values.
Valid values examples:
- 34.5
- 34.0
- 34
Invalid values examples:
- 34.2
- 34.8
- 34.6
I tried this one, but it doesn't work properly: [0-9]*[.]?[0|5]
Thank you very much guys!
CodePudding user response:
You're probably looking for [0-9]*(\.([50][0]*)*)*
.
[0-9]*
: Any character from 0 to 9, zero or more times [so that just a "." (= 0.0) input is valid]
\.
: You need to escape the '.' character, since it usually would mean "any character", and you especifically need the dot there.
[50][0]*
: First, either five or zero (once). Second, the 0 character, zero or more times (since 35.50 = 35.5). This also avoids inputs like 35.59 from being valid, since 9 != 0.
([50][0]*)*
: This occurrence zero or more times, so that 35., for instance, becomes a valid input (since 35. = 35.0).
(\.([50][0]*)*)*
: As for this grouping, it's in order to check for the five or the zero only if there is a decimal dot. It's grouping the dot character and the 5/0 logic together with a star (zero or more times) at the end, so if it doesn't occur, it still matches.
Let me know if this was what you were looking for.
CodePudding user response:
To verify the whole numbers in the examples, you can make the last part optional and use anchors.
^[0-9] (?:[.][05])?$
^
Start of string[0-9]
Match 1 digits 0-9(?:[.][05])?
Optionally match.
and a digit 0 or 5$
End of string
See a regex demo.
If you want to be able to only type a pattern like that and also accept empty strings or 34.
you can repeat the digit 0 or more times, optionally match .
and optionally match either 0 or 5.
^[0-9]*[.]?[05]?$
See another regex demo