查找浮点字符串时,正则表达式的行为很奇怪 [英] Regex behaving weird when finding floating point strings

查看:28
本文介绍了查找浮点字符串时,正则表达式的行为很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样做(在python 3.7.3中):

<预><代码>>>>从重新导入 findall>>>s = '7.95 + 10 件'>>>findall(r'(\d*\.)?\d+', s)['7.', ''] # 预期回报:['7.95', '10']

我不知道为什么它没有在里面找到所有的花车?这可能是关于捕获组的一些 Python 怪癖吗?

我的正则表达式背后的逻辑:(\d*\.)? 匹配 1 个或不匹配任何数量的数字,后跟一个句点.\d+ 然后匹配任意数量的数字,所以这个正则表达式应该匹配 11.11, 11, .11 等等.这里有什么问题吗?

解决方案

正如您猜对的那样,这与捕获组有关.根据 re.findall<的文档/a>:

<块引用>

如果模式中存在一个或多个组,则返回组列表

因此,您需要使所有组() 非捕获 使用 (?:) 说明符.如果没有捕获的组,它将返回整个匹配:

<预><代码>>>>模式 = r'(?:\d*\.)?\d+'>>>findall(模式,S)['7.95','10']

So doing this (in python 3.7.3):

>>> from re import findall
>>> s = '7.95 + 10 pieces'
>>> findall(r'(\d*\.)?\d+', s)
['7.', '']   # Expected return: ['7.95', '10']

I'm not sure why it doesn't find all the floats inside? Is this possibly some python quirk about capturing groups?

My logic behind the regex: (\d*\.)? matches either 1 or none of any number of digits, followed by a period. \d+ then maches any number of digits, so this regex should match any of 11.11, 11, .11 and so on. Whats wrong here?

解决方案

As you guessed correctly, this has to do with capturing groups. According to the documentation for re.findall:

If one or more groups are present in the pattern, return a list of groups

Therefore, you need to make all your groups () non-capturing using the (?:) specifier. If there are no captured groups, it will return the entire match:

>>> pattern = r'(?:\d*\.)?\d+'

>>> findall(pattern, s)
['7.95', '10']

这篇关于查找浮点字符串时,正则表达式的行为很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆