I have a regex that will validate to make sure I have a number. but it passed if the string I开发者_StackOverflow中文版'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
Rubular
To also allow matching .05:
^-?\d[\d,]*(?:\.\d+)?$|^-?\.\d+$
Rubular
Note that your expression also allows multiple commas one after another which may not be desirable.
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.
try
^-?([0-9]+)(,[0-9]+)?$
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".
This is the proper regex for grouped decimals:
^-?(?:\\.\\d+|\\d{1,3}(?:,\\d{3})*(\\.\\d*)?)$
- It accepts an initial sign.
- After that it creates a tree with two paths, either period or 1-3 digits.
- If it doesn't have either of those, it fails.
- If it sees a period, then it will take any number of digits, but at least 1.
- If it sees a digit cluster, it will take any number of groups consisting of comma + 3 digits.
- Then, you can have a decimal point, if you want and follow it up with as many digits as you would like.
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.
- If it's a digit, then nothing but a digit or a period can follow.
- Given a comma, nothing but 3 digits can follow. We intensified this to 1 or more, since
\\d*
handles the case of an immediate period.
精彩评论