Skip to content Skip to sidebar Skip to footer

How Does One Find The Currency Value In A String?

I'm writing a small tool to extract a bunch of values from a string (usually a tweet). The string could consist of words and numbers along with an amount prefixed by a currency sym

Solution 1:

>>> re.search(ur'([£$€])(\d+(?:\.\d{2})?)', s).groups()
(u'\xa3', u'6.50')
  • [£$€] matches one currency symbol
  • \d+(?:\.\d{2}) matches one or more digits followed by an optional decimal point followed by exactly two digits
  • The ()'s capture the symbol and amount separately

The problem with your regex is that .* matches anything and is greedy, so at the end of a regex it matches everything that follows.

Solution 2:

I've altered Marcog's regex altered a bit

    re.search(ur'([£\$€])(\d+(?:\.\d{2})?)', s).groups()

by escaping the dollar sign.

Post a Comment for "How Does One Find The Currency Value In A String?"