簡體   English   中英

正則表達式匹配字符串Python

[英]Regex for matching string Python

我想匹配一個字符串的數值:

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

re,findall()返回每個匹配項的所有捕獲組的元組,並且每組普通括號都會生成一個這樣的組。 像這樣編寫您的正則表達式:

size = re.findall(r'\d{1,3}(?:,\d{3})*(?:\.\d+)?', my_string)

說明:

\d{1,3}      # One to three digits
(?:,\d{3})*  # Optional thousands groups
(?:\.\d+)?   # Optional decimal part

假設所有數字都有逗號作為千位分隔符,即沒有數字像1000000 如果您也需要匹配它們,請使用

size = re.findall(r'\d+(?:,\d{3})*(?:\.\d+)?', my_string)

試試這個正則表達式:

(\$?\d+(?:[,.]?\d*(?:\.\d+)?)).*?

現場演示

為什么要對正則表達式進行分組? 試試這個r'\\$?\\d+,?\\d*\\.?\\d*'

我會嘗試此正則表達式:

r'[0-9] +(?:,[0-9] +) (?:。[0-9] )?'

加\\ $? 在開始時有選擇地捕獲$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM