gpt4 book ai didi

python正则表达式匹配美元值

转载 作者:行者123 更新时间:2023-11-30 22:03:35 25 4
gpt4 key购买 nike

我正在尝试在 Python 中提出一个用于美元值(value)搜索的正则表达式。我在 SO 帖子上查看并尝试了很多解决方案,但没有一个非常有效。

我想出的正则表达式是:

[Ss]        # OCR will mess up with dollar signs, so I'm specifically looking for S and s as the starting of what I'm looking for
\d+ # any digits to start off
(,\d{3})* # include comma for thousand splits, can have multiple commas
(.\d{2})? # include dot and 2 decimals, but only one occurrence of this part

我在以下示例中尝试过此操作:

t = "sixteen thousand three hundred and thirty dollars (s16,330.00)"
r = "[Ss]\d+(,\d{3})*(.\d{2})?"

re.findall(pattern=r, string=t)

我得到了:

[(',330', '.00')]

正则表达式文档说:

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. Empty matches are included in the result.

但它甚至没有得到整数部分。

我的问题是:我真的很想找到s16,330.00作为一个整体。有解决办法吗?

最佳答案

删除捕获组以允许 findall 返回完全匹配的字符串:

>>> t = "sixteen thousand three hundred and thirty dollars (s16,330.00)"
>>> r = r"[Ss]\d+(?:,\d{3})*(?:\.\d{2})?"
>>> re.findall(pattern=r, string=t)
['s16,330.00']

另请注意,正则表达式中的点需要转义

关于python正则表达式匹配美元值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53506795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com