llanato
llanato

Reputation: 2491

Python: Regular expression to get price from string error

I'm trying to make syre everything but numeric values and the decimal point are left in.

String

[\n\t\t€249.99\xa0\n\t\t\t]

Code

str(re.compile("^[0-9]\d*(\.\d+)?$", PRICE[0]))

Error

Traceback (most recent call last):
  File "getPrice.py", line 59, in <module>
    JSON_FILE.write("{\"price\":\"" + str(re.compile("^[0-9]\d*(\.\d+)?$", PRICE[0])) + "\"},")
  File "C:\...\Python\Python36-32\lib\re.py", line 233, in compile
    return _compile(pattern, flags)
  File "C:\...\Python\Python36-32\lib\re.py", line 301, in _compile
    p = sre_compile.compile(pattern, flags)
  File "C:\...\Python\Python36-32\lib\sre_compile.py", line 562, in compile
    p = sre_parse.parse(p, flags)
  File "C:\...\Python\Python36-32\lib\sre_parse.py", line 856, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, False)
TypeError: unsupported operand type(s) for &: 'lxml.etree._ElementUnicodeResult' and 'int'

Upvotes: 2

Views: 3052

Answers (1)

Gustavo Bezerra
Gustavo Bezerra

Reputation: 11034

You are incorrectly using re.compile. Here is a solution using re.search:

s = '\n\t\t€249.99\xa0\n\t\t\t'
re.search('[0-9.]+', s).group()   # Returns '249.99'

You can also achieve the same results using re.findall, re.match or re.sub.

Upvotes: 6

Related Questions