Regex to match different ways of expressing dollars

Viewed 31

I need to write a python regex expression to match the different ways of writing dollars:

$100

$1,000

$1,000.99

$50 millions

1 dollar

6 cents

50 dollars and 5 cents

5,000.6 dollars and 5 cents

I've managed to match the first 4 cases but I can't come up with something that will match the cases with the actual "dollars()" and "cent(s)" words

1 Answers

Your going to have to use separate groups or regexs

The first three (assuming you always use coma after 3 digits) \$\d{1,3}(,\d\d\d)*(\.\d\d)?

The 4th, usually people say million not millions but I made it work either way. \$\d{1,3}(,\d\d\d)* (billion|million|thousand|hundred)s?

\d+ dollars?

\d+ cents?

\d{1,3}(,\d\d\d) dollars? and \d+ cents?

Doesn't really make sense to do this one but here it is (why would you say 5.5 dollars and 7 cents instead of 5 dollars and 57 cents. \d+(\.\d\d?)? dollars? and \d+ cents?

you could then combine them into one massive regex if you want to but might be easier to read if you just do it multiple times and see what one (if any) are correct. ((\$\d{1,3}(,\d\d\d)*(\.\d\d)?)|(\$\d{1,3}(,\d\d\d)* (billion|million|thousand|hundred)s?)|(\d+ dollars?)|(\d+ cents?)|(\d+(\.\d\d?)? dollars? and \d+ cents?))

Related