2

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

Mazdak
  • 105,000
  • 18
  • 159
  • 188
alexcons
  • 531
  • 3
  • 8
  • 18
  • 1
    Clarification question: what are the minimum and maximum number of digits that you want to match? In general do you want to match any number composed of groups of 1-3 digits separated by commas with only the leading group having fewer than 3 digits? Or do you only care about numbers that are 1-9 digits long? – Engineero Jul 09 '15 at 15:22

3 Answers3

2

\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

Andris Leduskrasts
  • 1,210
  • 7
  • 16
1

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

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
1

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

Mazdak
  • 105,000
  • 18
  • 159
  • 188