8

我有以下内容:

temp = "aaaab123xyz@+"

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 仅匹配字符串的开头,我如何匹配中间的子字符串。

4

3 回答 3

14

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

似乎您在这里并不需要正则表达式。您的正则表达式123.35可能不符合您的预期,因为点匹配任何内容。

如果是这种情况,那么您可以使用x in s.

于 2010-04-23T07:27:22.560 回答
12

使用re.search或仅用于if l in temp:

注意:内置类型list不应该被遮蔽,这样for l in lists:更好

于 2010-04-23T07:27:27.183 回答
0

map您可以使用和进行稍微复杂的检查来做到这一点any

>>> temp = "aaaab123xyz@+"
>>> 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

我不确定这是否比编译的正则表达式更快。

于 2016-09-12T04:42:27.150 回答