使用python的re module,我试图从以下语句中获取美元值:
下面的模式适用于单个值,但如果有范围(如上面的第一个和最后一个点),它只给出最后一个数字(即349950和510000)。在
_pattern = r"""(?x)
^
.*
(?P<target1>
[€$£]
\d{1,3}
[,.]?
\d{0,3}
(?:[,.]\d{3})*
(?P<multiplyer1>[kKmM]?\s?[mM]?)
)
(?:\s(?:\-|\band\b|\bto\b)\s)?
(?P<target2>
[€$£]
\d{1,3}
[,.]?
\d{0,3}
(?:[,.]\d{3})*
(?P<multiplyer2>[kKmM]?\s?[mM]?)
)?
.*?
$
"""
当尝试target2 = match.group("target2").strip()
时,target2总是None
。在
我绝不是一个监管专家,但我不能真正看到我做错了什么。乘法器组工作正常,在我看来,target2组是相同的模式,也就是说,最后是可选匹配。在
我希望我的措辞有点可以理解。。。在
+1用于对regex模式使用详细模式
模式开头的
.*
是贪婪的,所以它试图匹配整行。然后它回溯以匹配target1。模式中的其他所有内容都是可选的,因此将target1与行中的最后一个匹配匹配是成功的匹配。您可以尝试通过添加“?”来使第一个.*
不贪婪是这样的:你能逐步做到吗?在
^{pr2}$编辑 还有一个想法:试试看关于芬德尔():
你可以想出一些正则表达式逻辑和一个转换缩写数字的函数相结合。下面是一些python代码示例:
代码使用了相当多的逻辑,它首先为
atof()
函数导入locale
模块,定义一个函数convert_number()
,并使用代码中解释的正则表达式搜索范围。显然,您可以添加其他货币符号,如€$£
,但它们不在您最初的示例中。在相关问题 更多 >
编程相关推荐