Regex to capture figure after pound symbol - amounts with commas and after a space not being captured

Viewed 93

my code is not capturing the amount after comma in a pound amount, or if the amount comes after a space.

Here is what I have so far:

finalcontent=' £2,500 and also £ 1200 and also £ 7,645 and finally £8888 and london'
    
price=[]
    # -*- coding: utf-8 -*-
    import sys
    import re

    new = re.findall(r'[£]{1}\d+\.?\d{0,2}',finalcontent,re.UNICODE)

    if len(new) != 0:
    
        for prices in new:

            dumistring=str(prices)
            price.append(re.sub("[^0-9.]","",dumistring))

        for ic in range(0, len(price)): 

            price[ic] = float(price[ic]) 

        avg_cost = sum(price)/len(price)

        pricinglist.append(avg_cost)

output is

price
[2.0, 8888.0]
2 Answers

I suggest using re.findall here:

finalcontent = ' £2,500 and also £ 1200 and also £ 7,645 and finally £8888 and london'
pounds = re.findall(r'£\s*((?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?)\b', finalcontent)
print(pounds)

This prints:

['2,500', '1200', '7,645', '8888']

Here is an explanation of the regex used:

£                    match a Pound symbol
\s*                  followed by optional whitespace
(                    capture what follows
    (?:
        \d{1,3}      1 to 3 digits
        (?:,\d{3})*  followed by zero or more comma separated thousands groups
        |            OR
        \d+          just one or more digits (for those numbers without commas)
    )
    (?:\.\d+)?       optional decimal component
)                    stop capturing
\b                   word boundary, indicating end of Pound number term

You can remove all commas in the string and use a much simpler pattern like

re.findall(r'£\s*(\d+(?:\.\d+)?)', finalcontent.replace(',',''))
# => ['2500', '1200', '7645', '8888']

See the Python demo. Note it will eliminate the need of the second regex later in the code, re.sub("[^0-9.]","",dumistring).

The £\s*(\d+(?:\.\d+)?) pattern means:

  • £ - a pound sign
  • \s* - zero or more whitespaces
  • (\d+(?:\.\d+)?) - Capturing group 1:
    • \d+ - one or more digits
    • (?:\.\d+)? - an optional non-capturing group matching one or zero occurrences of
      • \. - a period
      • \d+ - one or more digits

See the regex demo.

Related