Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 859
JoshBerke Avatar asked Feb 27 '23 10:02

JoshBerke


2 Answers

Try this regular expression:

/^[-+]?(?:\d*|\d{1,3}(?:,\d{3})*)(?:\.\d+)?$/
like image 103
Gumbo Avatar answered Mar 01 '23 23:03

Gumbo


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
like image 30
CaffGeek Avatar answered Mar 02 '23 01:03

CaffGeek