JoshBerke
JoshBerke

Reputation: 67128

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:

How can I have the expression indicate that if there is a comma then there must be three characters after it.

Upvotes: 4

Views: 1802

Answers (5)

Brian Lacy
Brian Lacy

Reputation: 19118

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.

Upvotes: 1

CaffGeek
CaffGeek

Reputation: 22064

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

Upvotes: 1

Gumbo
Gumbo

Reputation: 655785

Try this regular expression:

/^[-+]?(?:\d*|\d{1,3}(?:,\d{3})*)(?:\.\d+)?$/

Upvotes: 6

flaxeater
flaxeater

Reputation: 690

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!

Upvotes: 0

Pointy
Pointy

Reputation: 414006

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).

Upvotes: 0

Related Questions