Testing for numeric input with regular expression

I have the following regex:

^[-+]?[\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 interested in scientific notation, but my users may or may not type commas. The problem I am facing is that the expression matches:

  • 100,
  • 100.00

How can I show that if there is a comma, there should be three characters after it.

+4
source share
5 answers

Try this regex:

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

try it

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

ACHIEVEMENTS

 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 
+1
source

As Robert Harvey said, if all that bothers you is capturing numerical values ​​for use in your program, you can just break the commas and everything will be fine.

However, assuming this is a formatting issue (i.e. you check keystrokes and allow valid input or reformat the input as a valid numeric value), you can try something like this:

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

What this does is allow any number of comma sets and 3 digits, followed by zero or one set of points, followed by one or more digits.

+1
source

You put your β€œcounting” qualifiers in square brackets, which does not make sense (well it makes sense, syntactically, but it does not do what you think it does).

0
source

Why not just hit all the commas and then check?

 g=oldstring.replace(',',''); g=g.replace('.','');//may as well do dots too if (! g.match('/^[0-9]*[0-9]$/')) alert("Bummerific"); 

Also, if you want to resolve the comma, you should not place commas every 3 digits. International users use commas to separate decimal places. In this case, if you want to be pedantic, this regex will probably work

 /^[0-9][0-9,.]*[0-9]$/ 

Good luck

0
source

Source: https://habr.com/ru/post/1303145/


All Articles