简体   繁体   中英

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

Currently i am using this regex to match for positive numbers with a single decimal point

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

But this doesn't allow commas. How can i modify this to allow zero or more commas before the decimal point?

Example :

  • 11,111.00 (should be allowed) I am okay with numbers having any number of comma's before decimal point.

EDIT:

Valid values

  • 111
  • 11,111
  • 11,111.0
  • 111111

The values can be entered with or without comma. The datatype of this field is SQL MONEY, so it will handle comma's.

need

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

See the regex demo

Details

  • ^ - start of string
  • (?:\\d{1,3}(?:,\\d{3})*|\\d+) - Either of:
    • \\d{1,3}(?:,\\d{3})* - 1 to 3 digits followed with 0+ sequences of a , and 3 digits
    • | - or
    • \\d+ - 1 or more digits
  • (?:\\.\\d+)? - an optional sequence of . and 1+ digits
  • $ - end of string.

 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)); } 

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

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

[\\d,] will match digits or commas.
You could make the regex more complicated if you really need it to be more specific.

I would use this

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

See demo and explanation

This is pretty hard to read but I'll explain it

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

All the ?: are just to explicitly say to the regex engine "Don't capture the following group matched by this paren).

The simplified version would be

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

But it'd capture a lot of matching groups for no reason so I removed them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM