-3

It needs to match these

  • '42'
  • '1,234'
  • '6,368,745'

but not the following:

  • '12,34,567' (which has only two digits between the commas)
  • '1234' (which lacks commas)

I been using site such as http://www.regexpal.com/ to test out expressions.

I tried

  • ^\d{1,3}(,\d{3})*$
  • (\d{1,3},)*(\d{1,3})$
  • ([0-9]{1,3},)*([0-9]{1,3})$
  • [0-9]{1,3}((,[0-9]){1,3})*

but it doesn't work.

Could someone explain what's wrong with my attempts and an model answer?

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397

2 Answers2

1
^([0-9]{1,3})(,[0-9]{3})*$

Should do what you are after. I usually use http://pythex.org/ to test python regex strings.

mowcow
  • 81
  • 4
0

I think the following pattern will fit your need.
It allows the accepted numbers to be preceded by a comma not preceded by a digit, and to be followed by a comma not followed by a digit.

pati = ('(?<!\d,)(?<!\d)'
        '('
        '\d{1,3}'  '(?:,\d\d\d)*'
        ')'
        '(?!,\d)(?!\d)'
        )

rgx= re.compile(pati) 
eyquem
  • 24,028
  • 6
  • 35
  • 41