regex to match number comma number

后端 未结 3 989
有刺的猬
有刺的猬 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条回答
  •  旧时难觅i
    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+)?$
    

提交回复
热议问题