Reputation: 561
This is more a question for my own curiosity. I have a working solution, but I'm curious if anybody has any insight as to why one solution works and the other does not.
I needed a regular expression to validate a user has entered a valid number. Some examples:
87
887.65
-87
-87.65
My first attempt looked like this:
^(\-?[0-9]+(\.[0-9]*)?)$
It worked great except strings like '7x', '1a', '89p' were accepted. My new solution is below, and it seems to work just fine:
^(\-?[0-9]+(\.[0-9]+)?)$
The second one (note the '+') is slightly more concise, but I fail to see why the first one accepted letters and the second one doesn't. Does anybody see what I'm missing?
Upvotes: 2
Views: 165
Reputation: 1688
The "." in your regex is for the character "." literally, so it should be escaped "\.", otherwise it will match any character. In the second regex the "+" operator demands at least one decimal so it wont match "7x", but it will match "7x1", see this Regex demo
Upvotes: 1