Hi, I have a regex that will validate to make sure I have a number. but it passed if the string I'm checking is "" as well. how can I make a "" fail?
^(\\d|-)?(\\d|,)*\\.?\\d*$
Hi, I have a regex that will validate to make sure I have a number. but it passed if the string I'm checking is "" as well. how can I make a "" fail?
^(\\d|-)?(\\d|,)*\\.?\\d*$
You could require at least one digit:
^-?\d[\d,]*(?:\.\d+)?$
^^
required
To also allow matching .05:
^-?\d[\d,]*(?:\.\d+)?$|^-?\.\d+$
Note that your expression also allows multiple commas one after another which may not be desirable.
How about...
^-?\d+(,\d{3})*(\.\d+)?$|^-?\.\d+$
Tested it on Rubular, which is awesome (thanks, Mark!) It'll accept some sloppy comma management, like "1234,567", but will reject obvious crap like "123,,,,456".
What language are you using? There's undoubtedly a better way for you to detect "is this a number?" than rolling your own regex from scratch. If you're using Perl, then look at the Regexp::Common module that provides dozens of time-tested regexes for your use.
This is the proper regex for grouped decimals:
^-?(?:\\.\\d+|\\d{1,3}(?:,\\d{3})*(\\.\\d*)?)$
The following fix handles ungrouped numbers as well:
^-?(?:\\.\\d+|\\d{1,3}(?:\\d*|(?:,\\d{3})+)(\\.\\d*)?)$
But it does not allow somebody to include more than 3 in a group. Thus after 1-3 digits, there must be another digit or a comma or a period or the end.
\\d*
handles the case of an immediate period.