2

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?

Tushar
  • 85,780
  • 21
  • 159
  • 179
mike
  • 536
  • 1
  • 6
  • 16

1 Answers1

1

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

Lucas Araujo
  • 1,648
  • 16
  • 25
  • Apologies, there's a copy/paste error here. In my code I escape the first dash and the dot, but StackOverflow seems to be stripping them out for some reason. However, somehow the dot is not being properly escaped and you are correct, it's matching '7x1'. Confused. – mike Apr 28 '16 at 13:18
  • Ok, just needed to double escape the slash, because, Angular. Thanks @lbarros – mike Apr 28 '16 at 13:21
  • Glad I could help :) – Lucas Araujo Apr 28 '16 at 13:23