2013-03-28 41 views
0

原始字符串我要讀的線中,我尋找圖案像蟒:創建的變量

width:40 
height :50 
left : 60 
right: 70 

以下發現在上面的代碼中所需的圖案

line = "width:40" 
match = re.search(r'width\s*:\s*\d+', line) 

我已經硬編碼爲width

正則表達式模式我已存儲的所有四個變量在陣列key_word = ['width', 'height', 'left', 'right']

我要搜索的模式,所有這些變量像

for key in key_word: 
     match = re.search(key, line) 

問題是我怎麼能做出這種key一個原始的字符串,像

r'width\s*:\s*\d+' 
r'height\s*:\s*\d+' 
r'left\s*:\s*\d+' 
r'right\s*:\s*\d+' 

回答

1

我會做類似的如下:

key_word = ['width', 'height', 'left', 'right'] 
regex_template = r'{}\s*:\s*\d+' 
for key in key_word: 
    print re.search(regex_template.format(key), line) 
0

模式爲什麼不能用split(或partition)和strip

for line in lines: 
    key, sep, value = line.partition(':') 
    key = key.strip() 
    value = value.strip() 

如果你真的需要使用正則表達式,你可以格式化他們,太:

r'%s\s*:\s*\d+' % 'width' 

或者爲每個鍵:

regexes = [r'%s\s*:\s*\d+' % key for key in ['width', 'height', ...]] 
1

您也可以只使用一個通用的正則表達式:

matches = re.findall(r'(.*?)\s*:\s*(\d+)', text) 

matches將是(key, value)元組的列表。

0

您不需要此任務的正則表達式。查看其他答案。

但是如果你堅持,你可以創建一個動態使用re.escape

import re 

key_word = ['width', 'height', 'left', 'right'] 

myre = r'({})\s*:\s*(\d+)'.format('|'.join(map(re.escape, key_word)))