Matching numbers with regular expressions — only digits and commas

前端 未结 10 1620
旧时难觅i
旧时难觅i 2020-11-22 08:07

I can\'t figure out how to construct a regex for the example values:

123,456,789
-12,34
1234
-8

Could you help me?

10条回答
  •  故里飘歌
    2020-11-22 08:26

    ^[-+]?(\d{1,3})(,?(?1))*$
    

    Regular expression visualization

    Debuggex Demo

    So what does it?!

    • ^ marks the beginning of the string
    • [-+]? allows a minus or plus right after the beginning of the string
    • (\d{1,3}) matches at least one and max three ({1,3}) digits (\d - commonly [0-9]) in a row and groups them (the parenthesises (...) builds the group) as the first group
    • (,?(?1))* ok... let's break this down
      • (...) builds another group (not so important)
      • ,? matches a comma (if existent) right after the first sequence of digits
      • (?1) matches the pattern of the first group again (remember (\d{1,3})); in words: at this point the expression matches a sign (plus/minus/none) followed by a sequence of digits possibly followed by a comma, followed by another sequence of digits again.
      • (,?(?1))*, the * repeats the second part (comma & sequence) as often as possible
    • $ finally matches the end of the string

    the advantage of such expressions is, to avoid to define the same pattern within your expression again and again and again... well, a disadvantage is sometimes the complexity :-/

提交回复
热议问题