Regex in javascript to only allow numbers, commas and one decimal point

I am currently using this regex to match positive numbers with a single decimal point

/^\d+(\.\d+)?$/ 

But that does not allow commas. How can I change this to allow a decimal point to resolve zero or more commas?

Example:

  • 11111.00 (should be allowed) I'm fine with numbers that have any number of commas to a decimal point.

EDIT:

Valid Values

  • 111
  • 11111
  • 11,111.0
  • 111111

Values โ€‹โ€‹can be entered with or without a comma. The data type of this field is SQL MONEY, so it will process a comma.

+5
source share
4 answers

required

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

Watch the regex demo

More details

  • ^ - start of line
  • (?:\d{1,3}(?:,\d{3})*|\d+) - Any of:
    • \d{1,3}(?:,\d{3})* - from 1 to 3 digits, followed by 0 + sequences , and 3 digits
    • | - or
    • \d+ - 1 or more digits
  • (?:\.\d+)? - optional sequence . and 1 + digits
  • $ is the end of the line.

 var strs = [',,,,', '111', '11,111', '11,111.0', '111111']; var re = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/; for (var s of strs) { console.log(s + " => " + re.test(s)); } 
+3
source

This is a very simple general solution, without any assumptions about how many numbers are needed.

 /^\d[\d,]*(\.\d+)?$/ 

[\d,] will match numbers or commas.
You can make the regex more complex if you really need it to be more specific.

+1
source

I would use this

 ^(?:\d{1,3}(,\d{3})*|\d+|\d{2}(?:,\d{2})*,\d{3})(?:\.\d+)?$ 

See demo and explanation.

+1
source

It's pretty hard to read, but I will explain it.

/^(?:\d+)(?:(?:\d+)|(?:(?:,\d+)?))+(?:\.\d+)?$/

Everyone ?: Should simply explicitly indicate the regex engine "Do not record the next group matched by this pair."

The simplified version will be

/^(\d+)((\d+)|((,\d+)?))+(\.\d+)?$/

But he would capture many suitable groups for no reason, so I deleted them

0
source

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


All Articles