2014-01-21 104 views
0

我想用正則表達式在此表達的一個文件中搜索:Python的正則表達式搜索

time:<float> s 

我只想要得到的浮點數。 我學習正則表達式,這就是我所做的:

astr = 'lalala time:1.5 s\n' 
p = re.compile(r'time:(\d+).*(\d+)') 
m = p.search(astr) 

嗯,我從m.group(0) time:1.5我怎麼能直接先手1.5

回答

0

你可以做創建另一組爲。而且我還會稍微改變正則表達式以允許沒有小數點分隔符的數字。現在

re.compile(r'time:((\d+)(\.?(\d+))?') 

可以使用group(1)捕捉浮點數的比賽。

0

我想你真正想要的正則表達式是更多的東西一樣:

re.compile(r'time:(\d+\.\d+)') 

甚至:

re.compile(r'time:(\d+(?:\.\d+)?)') # This one will capture integers too. 

請注意,我已經把整個時間爲1組。我也逃過了.這意味着正則表達式中的任何字符。

然後,你會得到1.5m.group(1) - m.group(0)整個比賽。 m.group(1)是第一個子匹配(括號分組),m.group(2)是第二分組等

例如:

>>> import re 
>>> p = re.compile(r'time:(\d+(?:\.\d+)?)') 
>>> p.search('time:34') 
<_sre.SRE_Match object at 0x10fa77d50> 
>>> p.search('time:34').group(1) 
'34' 
>>> p.search('time:34.55').group(1) 
'34.55' 
1

因爲你說你正在學習正則表達式,所以我包含了一些額外的python特定的材料。正如已經提到的那樣,最簡單的正則表達式肯定是\d+\.\d+,如下所述的各種命令。

最初用python把我扔掉的東西是讓我的腦袋圍繞各種方法的返回類型以及何時使用group()與groups()。

有幾種方法,您可以使用:

  • re.match()
  • re.search()
  • re.findall()

match()只會返回一個如果在字符串的開頭找到該模式,則返回對象。 search()會找到第一個模式和頂部。 findall()會在字符串中找到所有內容。

match()和search()的返回類型是匹配對象,__Match [T]或None,如果找不到匹配項。然而,findall()的返回類型是一個列表[T]。這些不同的回報類型顯然會對您如何從匹配中獲取值產生影響。

這兩個匹配和搜索都暴露了group()和groups()方法來檢索您的匹配。但是,當使用findall時,您需要遍歷列表或使用枚舉器來提取值。因此,使用的findall:

>>>import re 
>>>easy = re.compile(r'123') 
>>>matches = easy.findall(search_me) 
>>>for match in matches: print match 
123 

如果你使用搜索()或匹配(),您需要使用。集團()或組(),這取決於你如何設置檢索你的對手你的正則表達式。

documentation開始,「groups()方法返回一個包含所有子組的字符串的元組,從1到最多的子組。

因此,如果你在你的正則表達式沒有組,如下面的例子,你不會得到任何東西:

>>>import re 
>>>search_me = '123abc' 
>>>easy = re.compile(r'123') 
>>>matches = easy.search(search_me) 
>>>print matches.groups() 
() 

添加一個「小組」,正則表達式,您可以使用此:

>>>import re 
>>>search_me = '123abc' 
>>>easy = re.compile(r'(123)') 
>>>matches = easy.search(search_me) 
>>>print matches.groups() 
('123',) 

您不必在正則表達式中指定組。即使您的表達式中沒有括號中的任何內容,group(0)或group()也會返回整個匹配。 --group()默認爲組(0)。

>>>import re 
>>>search_me = '123abc' 
>>>easy = re.compile(r'123') 
>>>matches = easy.search(search_me) 
>>>print matches.group(0) 
123 

如果使用圓括號,可以使用組匹配特定的組和子組。

>>>import re 
>>>search_me = '123abc' 
>>>easy = re.compile(r'((1)(2)(3))') 
>>>matches = easy.search(search_me) 
>>>print matches.group(1) 
>>>print matches.group(2) 
>>>print matches.group(3) 
>>>print matches.group(4) 
123 
1 
2 
3 

我想指出,除非您關心可用性和/或可讀性的原因,否則您不必編譯您的正則表達式。它不會改善你的表現。

>>>import re 
>>>search_me = '123abc' 
>>>#easy = re.compile(r'123') 
>>>#matches = easy.search(search_me) 
>>>matches = re.search(r'123', search_me) 
>>>print matches.group() 

希望這有助於!我發現debuggex等網站在學習正則表達式時很有幫助。 (雖然有時候你必須刷新這些頁面;但是在我意識到重新加載頁面之後,我在一個晚上敲了我的頭幾個小時,然後我的正則表達式工作得很好。)最近我認爲你也可以通過拋出沙盒代碼到像wakari.io這樣的東西,或像PyCharm這樣的IDE,並觀察輸出。 http://www.rexegg.com/也是一個普通的正則表達式知識的好網站。