正则表达式在查找浮点字符串时表现得很奇怪

Regex behaving weird when finding floating point strings

这样做(在 python 3.7.3 中):

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

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

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

如您所料,这与捕获组有关。根据 re.findall 的文档:

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

因此,您需要使用 (?:) 说明符将所有组设为 () non-capturing。如果没有捕获的组,它将 return 整个匹配:

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

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