Python:正则表达式从字符串错误中获取价格

时间:2017-04-27 07:39:42

标签: python regex python-3.x

我正在努力制作syre,但数字值和小数点都留在了。

字符串

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

代码

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

错误

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'

1 个答案:

答案 0 :(得分:2)

您错误地使用了re.compile。以下是使用re.search的解决方案:

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

您还可以使用re.findallre.matchre.sub获得相同的结果。