首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python:从字符串错误中获取价格的正则表达式

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

Stack Overflow用户
提问于 2017-04-27 07:39:41
回答 1查看 2.7K关注 0票数 2

我试着让syre除了数值和小数点之外的所有东西都留在里面。

字符串

代码语言:javascript
运行
复制
[\n\t\t€249.99\xa0\n\t\t\t]

代码语言:javascript
运行
复制
str(re.compile("^[0-9]\d*(\.\d+)?$", PRICE[0]))

误差

代码语言:javascript
运行
复制
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'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-27 07:48:06

您使用re.compile是错误的。下面是使用re.search的解决方案

代码语言:javascript
运行
复制
s = '\n\t\t€249.99\xa0\n\t\t\t'
re.search('[0-9.]+', s).group()   # Returns '249.99'

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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43651480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档