[英]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
进行简单的字符串包含。
You can do this with a slightly more complex check using map
and any
. 您可以使用
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
I'm not sure if this is faster than a compiled regexp. 我不确定这是否比编译的正则表达式更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.