2017-08-05 77 views
0

我得到的數據集這樣的(它開闢爲STR從文件):正則表達式匹配一個或多個數字

MF8='out1mf8':'constant',[1944.37578865883] 
MF9='out1mf9':'constant',[2147.79853787502] 
MF10='out1mf10':'constant',[565.635908155949] 
MF11='out1mf11':'constant',[0] 
MF12='out1mf12':'constant',[0] 

我需要在括號中這個值,所以創建正則表達式:

outmfPattern = 'out\dmf\d' 

並用:

re.findall(outmfPattern, f) 

它的工作很好,直到mf = 9。有人有想法如何處理這個?

+0

''out \ dmf \ d +''''''指定一個或多個匹配項。 –

回答

5

讓我們打破你的正則表達式out\dmf\d

  • out序列'out'
  • \d相匹配的數字
  • mf匹配序列'mf'
  • \d相匹配的數字
匹配

如果您想匹配out1mf11之類的東西,您需要在末尾查找數字。

您可以使用out\dmf\d+,或者,如果你想在年底匹配只有1或2數字,out\dmf\d{1,2}


In [373]: re.findall('out\dmf\d+', text) 
Out[373]: ['out1mf8', 'out1mf9', 'out1mf10', 'out1mf11', 'out1mf12'] 

此外,如果你想括號添加到這些搜索條目的,你應該看看re.sub代替:

In [377]: re.sub('(out\dmf\d+)', r'(\1)', text) 
Out[377]: "MF8='(out1mf8)':'constant',[1944.37578865883] MF9='(out1mf9)':'constant',[2147.79853787502] MF10='(out1mf10)':'constant',[565.635908155949] MF11='(out1mf11)':'constant',[0] MF12='(out1mf12)':'constant',[0]" 

re.sub替換捕獲組與包圍的同在parens。

相關問題