2013-03-28 40 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)))