我想匹配字符串的数值:

1,000 metric tonnes per contract month
Five cents ($0.05) per tonne
Five cents ($0.05) per tonne
1,000 metric tonnes per contract month

我目前的做法:
size = re.findall(r'(\d+(,?\d*).*?)', my_string)

我的方法得到了什么:
print size
[(u'1,000', u',000')]

如您所见,从列表的第二个元素中删除了数字 1,这是为什么呢?另外,我能否得到有关如何匹配 $0.05 术语的提示?

最佳答案

像这样的东西:

>>> import re
>>>  strs = """1,000 metric tonnes per contract month
Five cents ($0.05) per tonne
Five cents ($0.05) per tonne
1,000 metric tonnes per contract month"""
>>> [m.group(0) for m in re.finditer(r'\$?\d+([,.]\d+)?', strs)]
['1,000', '$0.05', '$0.05', '1,000']

演示:http://rubular.com/r/UomzIY3SD3

关于python - 用于匹配字符串 Python 的正则表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17213180/

10-13 03:53