Python 正则表达式在与 re.findall 一起使用时返回匹配的一部分

标签 python regex findall

我一直在尝试自学 Python,目前正在学习正则表达式。我一直在使用的说明文本似乎旨在教授 Perl 或其他一些非 Python 的语言,因此我不得不稍微调整一下表达式以适应 Python。然而,我不是很有经验,而且我在尝试让表达式起作用时遇到了障碍。

该问题涉及在文本中搜索价格实例,以不带小数的 $500 或带小数的 $500.10 表示。

这是文本推荐的内容:

\$[0-9]+(\.[0-9][0-9])?

复制文本,我使用这段代码:

import re

inputstring = "$500.01"

result = re.findall( r'\$[0-9]+(\.[0-9][0-9])?', inputstring)

if result:
    print(result)
else:
    print("No match.")

但是,结果不是 $500.01,而是:

.01

我觉得这很奇怪。如果我删除括号和可选的小数部分,它就可以正常工作。所以,使用这个:

\$[0-9]+\.[0-9][0-9]

我得到:

$500.01

如何让正则表达式返回带小数部分和不带小数部分的值?

谢谢。

最佳答案

使用非捕获组:

result = re.findall( r'\$[0-9]+(?:\.[0-9][0-9])?', inputstring)
                                ^^ 

re.findall如果模式中定义了任何内容,函数将返回捕获的文本列表,而您也有一个。您需要通过将其变成非捕获的来摆脱它。

re.findall(pattern, string, flags=0)
If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

更新

您可以通过使用限制量词 {2} 稍微缩短您的正则表达式,它需要前面的子模式恰好出现 2 次:

r'\$[0-9]+(?:\.[0-9]{2})?'
                    ^^^

甚至用 \d 替换 [0-9]:

r'\$\d+(?:\.\d{2})?'

关于Python 正则表达式在与 re.findall 一起使用时返回匹配的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32105484/

相关文章:

python - 透明窗口背景(Python Tkinter)

python - 通过 Excel 在 CSV 中保留前导 "+"

regex - 完全匹配 Perl 字符串中包含的以 $(或特殊字符)开头的单词

JavaScript JS 可选

c# - 匹配 href 的正则表达式,但没有媒体文件

Python 的正则表达式 findall 不返回 Unicode 文本的所有匹配项

python - `with open` 多个 `findall` 但打开文件一次

python - 查找错误 : No installed app with label 'user'

python - 尝试在 Python 中搜索带有 (.*?) 的字符串

python - 安装 deeptools 时如何解决 UnsatisfiableError?