I try to make a regular expression in Javascript to validate text strings that can be of the following form:
- Any number from 3.0 to 5.0 in steps of 0.1 (3.0, 3.1, 3.2...)
- The numbers 3, 4 and 5, and
- The strings 3., 4. and 5. (with the period at the end)
The expression I got for these cases is /(3|4)((\.?)|(\.[0-9]))|(5(\.?)0?)/
that it matches the numbers 3, 4 and 5 and the strings 3., 4., 5. but I don't get the numbers like 3.1, 3.2, etc. nor the 5.0 as indicated by Regex 101 ? What did I do wrong in my regular expression?
Try the following regular expression:
The order of the factors affects the result. In this part:
First comes the comparison with the
.
and then with the.x
(with x a number between 0 and 9), so the first is true and the second is ignored. A possible solution would be to change the order:With that it already recognizes you 3.0, 3.1, 3.2...
Now, to accept 5.0 but not 50, you can follow a similar method:
That would know either the empty string (for 5), or
.
, or.0
but no other value.Putting all the changes together, the regular expression would look like this
Grades: