I have the following regular expression:
^[-+]?[\d{0,3},?\d{3}]*\.?\d+$
I am trying to support numbers of the following formats:
- 1
- -1开发者_运维百科
- -1.00
- 100,000
I am not concerned about scientific notation but my users may or may not enter in commas. The problem I am having is that the expression is matching:
- 100,
- 100,00
How can I have the expression indicate that if there is a comma then there must be three characters after it.
Try this regular expression:
/^[-+]?(?:\d*|\d{1,3}(?:,\d{3})*)(?:\.\d+)?$/
Try this
^([-+]?\d(?:(,\d{3})|(\d*))+\d*)?\.?\d*$
SUCCESSES
0
1
-1
-1.00
100,000
100.0
1,111,111
.25
FAILURES
100.0.
100.0,
asdf100.0
100,
1,11,111
,111,111
As Robert Harvey indicated, if all you're concerned about is capturing numeric values to use in your program, you can just strip out the commas and all will be well.
However, assuming this is a formatting question (that is, you're checking keystrokes and only allowing valid input, or reformatting the input to be a valid numeric value), then you could try something like this:
EDIT: ^[+-]?\d{1,3}(,\d{3})*(\.\d+)?$
What this does is allow any number of sets of a comma and 3 digits, followed by zero or one set of a dot followed by one or more digits.
You've put your "count" qualifiers inside square brackets, which doesn't make sense (well it makes sense, syntactically, but it's not doing what you think it's doing).
Why not just whack all commas and then test?
g=oldstring.replace(',','');
g=g.replace('.','');//may as well do dots too
if (! g.match('/^[0-9]*[0-9]$/'))
alert("Bummerific");
Additionally if you're going to allow commas then you shouldn't make them place commas every 3 digits. International users use commas to separate decimal place. In which case if you wanna be pedantic then this regex will probably work
/^[0-9][0-9,.]*[0-9]$/
Good Luck!
精彩评论