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?
^[-+]?(\d{1,3})(,?(?1))*$
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 stringthe 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 :-/