I am trying to write a regex for allowing 3 digit numbers followed by optional decimal, integer part cant be greater than 180 or smaller than -180. example of valid enteries are 156.56, 56.778, 9, 6.7.etc etc.
So far I came up with this ^(\+|-)?:180|1[0-7][0-9]|[0-9][0-9]|[0-9]?([\.][0-9]{1,3})?$ but these seems to match 195.678 too.
I am trying to write a regex for allowing 3 digit numbers followed by
Share
Instead of doing that, why not just have two checks? One makes sure that you match the pattern, and the other makes sure that the value is between -180 and 180.
The resulting solution is far easier to understand and maintain, and not to mention, saner :).
The reason your regex doesn’t work is that the
^and$don’t match across the entire pattern. You have the different conditions in your regex that are separated by|. The^is associated with the first option, and the$is associated with the last option. This is easy to see in the following example:Assume you had the regex
/^[0-9][0-9]|[0-9]$/. If you tested this against12345what would you get? You might be inclined to say that it would returnfalse, but it actually returnstrue. This is because there is a valid match! The12in12345will match against^[0-9][0-9]. So what you’re saying is that you want to match against any two numbers at the beginning of the string or against a number at the end of the string. Basically any string that has at least two numbers at the beginning or one number at the end, will match. So12abcwill match, as willabc1.However, if you changed the regex to
/^([0-9][0-9]|[0-9])$/, only one and two-digit numbers will match. This is because the beginning and end-of-string anchors are outside the matching group, meaning the entire group has to match. This is something that you have to consider when you have conditions in your regex.EDIT
Also, Tim points out: