vendredi 1 juillet 2016

Extract any number with commas every three digits using regular expression [duplicate]

This question already has an answer here:

I am trying to extract numbers of the format 1, 10, 100, 1,000, 1,000,000 etc. using regular expression. After tinkering for a while, the closest I have come is:

numberRegex = re.compile(r'd{1,3}(?:,d{3})*')

But this doesn't work as expected:

numberRegex.findall('42,000, 42 and 1,000 are matched but 42,00 and 1000 are not.')

This gives the result:

['42,000', '42', '1,000', '42', '00', '100', '0']

I also tried using ^ and $ but no match is returned when this is done.

numberRegex = re.compile(r'^d{1,3}(?:,d{3})*$')

The result is an empty list. I read the string must match the regex formed exactly when this is done.

How do I get this result:

['42,000', '42', '1,000']

Aucun commentaire:

Enregistrer un commentaire