2010-04-23 117 views
8

我有以下几点:的Python:列表和字符串匹配

temp = "[email protected]+" 

lists = ["abc", "123.35", "xyz", "AND+"] 

for list in lists 
    if re.match(list, temp, re.I): 
    print "The %s is within %s." % (list,temp) 

的re.match仅仅是匹配的字符串,如何我也匹配之间的子串的开始。

回答

14

您可以使用re.search而不是re.match

这似乎也并不需要正则表达式。你的正则表达式123.35可能不符合你的期望,因为这个点匹配任何东西。

如果是这种情况,那么你可以使用x in s做简单的字符串遏制。

+0

是的,你的实际速度是5秒,+1 – YOU 2010-04-23 07:32:30

12

使用re.searchif l in temp:

注意只需使用:内置list型不应该被隐藏,所以for l in lists:更好

+0

我不得不同意简单的子串匹配'in'比re.search要容易得多。 – fantabolous 2014-07-29 03:26:38

0

可以使用map一个稍微更复杂的检查做到这一点, any

>>> temp = "[email protected]+" 
>>> lists = ["abc", "123.35", "xyz", "AND+"] 
>>> any(map(lambda match: match in temp, lists)) 
True 
>>> temp = 'fhgwghads' 
>>> any(map(lambda match: match in temp, lists)) 
False 

我不知道这是不是一个编译的正规表达式更快。