开发者

Testing for numeric input with regular expression

I have the following regular expression:

^[-+]?[\d{0,3},?\d{3}]*\.?\d+$

I am trying to support numbers of the following formats:

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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜