Regex validation for numbers with comma separator

前端 未结 3 1342
情深已故
情深已故 2020-12-03 18:44

Need a regular expression to validate number with comma separator. 1,5,10,55 is valid but 1,,,,10 is not valid.

相关标签:
3条回答
  • 2020-12-03 19:15
    ^[0-9]*(,){1}[0-9]*/
    

    try this

    0 讨论(0)
  • 2020-12-03 19:27

    This should do it:

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

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

    You may want to throw in \s* where you see fit, or remove all spaces before validation.

    • To allow negative numbers replace \d+ with [+-]?\d+
    • To allow fractions: replace \d+ with [+-]?\d+(?:\.\d+)?
    0 讨论(0)
  • 2020-12-03 19:37

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

    • \d is the shorthand for the digit character class
    • + is one-or-more repetition specifier
    • * is zero-or-more repetition specifier
    • (...) performs grouping
    • ^ and $ are the beginning and end of the line anchors respectively

    We can now compose the regex we need:

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

    That is:

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

    Note that the * means that having just one number is allowed. If you insist on at least two numbers, then use + instead. You can also replace \d+ with another pattern for the number to allow e.g. sign and/or fractional part.

    References

    • regular-expressions.info/Repetition, Character Classes, Grouping, Anchors

    Advanced topics: optimization

    Optionally you can make the brackets non-capturing for performance:

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

    And if the flavor supports it, you can make all repetition possessive in this case:

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

    References

    • regular-expressions.info/Possessive
    0 讨论(0)
提交回复
热议问题