alexcons
alexcons

Reputation: 531

Regex help needed to match numbers

I am an absolute noob at regex and need to help to match numbers in this format:

1,234,567 

or

123,456

Including the commas! So I would like to match for example:

980,232  905,903  889,614  881,145  2,343,435  3,435,123

Extra note: I am using python re module

Upvotes: 2

Views: 82

Answers (3)

Andris Leduskrasts
Andris Leduskrasts

Reputation: 1230

\d{1,3}(?:,\d{3})* to match correctly placed commas (4,43,424 won't match)

https://regex101.com/r/kQ6fC9/3

There can be 1-3 digits before the first comma, and then (,xyz) can repeat however times it wants, -,123,456, ,123,456,789 and also no times - just a number 13.

This works perfectly for whole (integer) numbers that may be divided by commas for readability. If you need to add also decimals to it, it means that the number after the last comma has no limitations. (?<=^|\s)\d{1,3}(?:,\d{3})*(?:,\d+)?(?=\s|$) should work for any number, including decimals, while avoiding faulty ones, https://regex101.com/r/kQ6fC9/4

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107347

You can use following regex :

^(?:\d,)?\d{3},\d{3}$

See the demo https://regex101.com/r/yY3xR6/1

And read more about regex repetition http://www.regular-expressions.info/repeat.html

Upvotes: 1

Andrey Korneyev
Andrey Korneyev

Reputation: 26886

Well, conditions you've stated are little bit vague. If you want to match any combinations of digits separated by commas you can use following pattern (yes, it is kinda broad): [\d,]+

See demo

Upvotes: 1

Related Questions