简体   繁体   English

Python:列表和字符串匹配

[英]Python: list and string matching

I have following: 我有以下内容:

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)

The re.match is only match the beginning of the string, How to I match substring in between too. re.match只匹配字符串的开头,如何在中间匹配子字符串。

You can use re.search instead of re.match . 您可以使用re.search而不是re.match

It also seems like you don't really need regular expressions here. 在这里你似乎并不需要正则表达式。 Your regular expression 123.35 probably doesn't do what you expect because the dot matches anything. 您的正则表达式123.35可能无法达到预期效果,因为点匹配任何内容。

If this is the case then you can do simple string containment using x in s . 如果是这种情况,那么您可以使用x in s进行简单的字符串包含。

Use re.search or just use in if l in temp: 使用re.search或只使用if l in temp:

Note : built-in type list should not be shadowed, so for l in lists: is better 注意 :内置类型list不应该被遮蔽,因此for l in lists:更好

You can do this with a slightly more complex check using map and any . 您可以使用mapany进行稍微复杂的检查。

>>> 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

I'm not sure if this is faster than a compiled regexp. 我不确定这是否比编译的正则表达式更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM