regex to match number comma number

后端 未结 3 987
有刺的猬
有刺的猬 2021-01-20 16:46

This is what I have right now:

^[0-9]([,][0-9])?$

My problem is that i want to be able add more than one digit before and after my comma. <

相关标签:
3条回答
  • 2021-01-20 17:15

    Use + sign, and also remove [] brackets around ,(they are not neccessary):

    ^[0-9]+(,[0-9]+)?$
      //  ^-------^---------here they are
    
    0 讨论(0)
  • 2021-01-20 17:38

    You have two regex main repeaters, the first is *, that say "repeat zero or more times". The second is + that say "repeat one or more time".

    In this case, you need repeat one or more times the integer value and the decimal value. So you can try it:

      ^[0-9]+([,][0-9]+)?$
    

    So it will validate:

      0
      0123
      1,12
      1,0
      1,12340
    

    But not will validate:

      1,
      ,0
      -1,0
      1e-10
    

    Tips:

    • You can replace [0-9] with only \d. It mean the same thing;
    • You don't need group comma, just use , instead of [,]. You use that only for more than one possibilities, like accept comma and dot: [,\.];

    Following the tips, you can try:

      ^\d+(,\d+)?$
    
    0 讨论(0)
  • 2021-01-20 17:40

    I'd suggest the following:

    /^\d+,\d+$/
    

    The + 'matches the preceding item one or more times.'

    References:

    • JavaScriptRegular Expressions,at Mozilla Developer Network.
    0 讨论(0)
提交回复
热议问题