2009-11-26 33 views

回答

14

參見:Python regex match objects

>>> import re 
>>> p = re.compile("lalala(I want this part)lalala") 
>>> p.match("lalalaI want this partlalala").group(1) 
'I want this part' 
4
import re 
data = "some input data" 
m = re.search("some (input) data", data) 
if m: # "if match was successful"/"if matched" 
    print m.group(1) 

查看docs瞭解更多信息。

1
import re 
match = re.match('lalala(I want this part)lalala', 'lalalaI want this partlalala') 
print match.group(1) 
10
import re 
astr = 'lalalabeeplalala' 
match = re.search('lalala(.*)lalala', astr) 
whatIWant = match.group(1) if match else None 
print(whatIWant) 

小記:在Perl中,當你寫

$string =~ m/lalala(.*)lalala/; 

正則表達式可以在字符串中的任何位置匹配。等效功能是使用re.search()函數完成的,而不是re.match()函數,它要求模式匹配從字符串的開頭開始。

17

如果你想通過名稱的部分,你也可以這樣做:

>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds") 
>>> m.groupdict() 
{'first_name': 'Malcom', 'last_name': 'Reynolds'} 

的例子來自re docs

2

採取沒有必要的正則表達式。認爲簡單。

>>> "lalala(I want this part)lalala".split("lalala") 
['', '(I want this part)', ''] 
>>> "lalala(I want this part)lalala".split("lalala")[1] 
'(I want this part)' 
>>> 
+0

非常聰明的想法:) – Linh 2016-04-01 18:09:53

0
import re 

string_to_check = "other_text...lalalaI want this partlalala...other_text" 

p = re.compile("lalala(I want this part)lalala") # regex pattern 
m = p.search(string_to_check)      # use p.match if what you want is always at beginning of string 

if m: 
    print m.group(1) 

在嘗試轉換Pe​​rl程序到Python是解析函數名出來的模塊,我就遇到了這個問題,我收到一個錯誤說「羣」是不明確的。我很快意識到這個例外正在被拋出,因爲p。 匹配 /頁。 搜索如果沒有匹配的字符串,則返回0。

因此,組操作員不能運行它。因此,爲避免發生異常,請檢查是否存儲了匹配項,然後應用組運算符。

import re 

filename = './file_to_parse.py' 

p = re.compile('def (\w*)')   # \w* greedily matches [a-zA-Z0-9_] character set 


for each_line in open(filename,'r'): 
    m = p.match(each_line)    # tries to match regex rule in p 
    if m: 
     m = m.group(1) 
     print m 
相關問題