admin管理员组

文章数量:1401922

Using JavaScript, I need to accept only numbers and mas.

The regex pattern I am using is as follows

 var pattern = /^[-+]?[0-9]+(\.[0-9]+)?$/;

How do I accept mas in the above pattern So that values like 3200 or 3,200 or 3,200.00 and so are valid?

There are similar questions that only partially deal with this:

  • Regex validation for numbers with ma separator (only whole numbers with no fractional part)
  • Decimal number regular expression, where digit after decimal is optional (no ma separation, fractional part limited to 1 digit)
  • Javascript function need allow numbers, dot and ma (the dots, mas and digits are matched in any order)

Using JavaScript, I need to accept only numbers and mas.

The regex pattern I am using is as follows

 var pattern = /^[-+]?[0-9]+(\.[0-9]+)?$/;

How do I accept mas in the above pattern So that values like 3200 or 3,200 or 3,200.00 and so are valid?

There are similar questions that only partially deal with this:

  • Regex validation for numbers with ma separator (only whole numbers with no fractional part)
  • Decimal number regular expression, where digit after decimal is optional (no ma separation, fractional part limited to 1 digit)
  • Javascript function need allow numbers, dot and ma (the dots, mas and digits are matched in any order)
Share Improve this question edited Aug 25, 2019 at 21:28 Wiktor Stribiżew 628k41 gold badges498 silver badges614 bronze badges asked Oct 27, 2015 at 12:54 user1339913user1339913 1,0274 gold badges16 silver badges37 bronze badges 1
  • 1 Why not test if the string is a valid number instead of trying to match it with a regex? – James Montagne Commented Oct 27, 2015 at 13:01
Add a ment  | 

1 Answer 1

Reset to default 4

Use the following regex:

^[-+]?(?:[0-9]+,)*[0-9]+(?:\.[0-9]+)?$

See regex demo

The basic change here is the addition of (?:[0-9]+,)* subpattern that matches:

  • [0-9]+ - 1 or more digits
  • , - a ma

0 or more times (thanks to * quantifier).

I also used non-capturing groups so that regex output is "cleaner".

If you need to check for 3-digit groups in the number, use

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

See another demo

Here, (?:,[0-9]{3})* matches 0 or more sequences of a ma and 3-digit substrings ([0-9]{3}). {3} is a limiting quantifier matching exactly 3 occurrences of the preceding subpattern.

本文标签: javascriptRegex to validate commaseparated numbers with optional fractional partsStack Overflow