Validating regular expressions for comma-separated numbers

A regular expression is required to validate a comma delimited number. 1,5,10,55 , but 1, 10 is invalid.

+6
jquery regex validation
source share
3 answers

This should do it:

^\d+(,\d+)*$ 

The regex is pretty simple: \d+ is the first number, followed by optional commas and other numbers.

You may want to insert \s* where you think it is necessary, or remove all spaces before checking.

  • So that negative numbers replace \d+ with [+-]?\d+
  • To resolve fractions: replace \d+ with [+-]?\d+(?:\.\d+)?
+11
source share

Here are the regex components we're going to use:

  • \d is short for character class
  • + is one or more repeat specifiers
  • * - repetition specifier with a zero or a large number
  • (...) grouping
  • ^ and $ are the beginning and end of line bindings, respectively

Now we can compose the regular expression we need:

 ^\d+(,\d+)*$ 

I.e:

 from beginning... | ...to the end | | ^\d+(,\d+)*$ ie ^num(,num)*$ \_/ \_/ num num 

Please note that * means that only one number is allowed. If you insist on at least two numbers, use + instead. You can also replace \d+ with another pattern for a number that allows, for example. sign and / or fractional part.

References


Advanced Topics: Optimization

Optionally, you can make the brackets not spectacular for performance:

 ^\d+(?:,\d+)*$ 

And if the fragrance supports it, you can make the whole repetition possessive in this case:

 ^\d++(?:,\d++)*+$ 

References

+8
source share
 ^[0-9]*(,){1}[0-9]*/ 

try it

0
source share

All Articles