Python:列表和字符串匹配
我有以下内容:
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 仅匹配字符串的开头,如何匹配中间的子字符串。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
re.search
而不是re.match
。看来您在这里并不真正需要正则表达式。您的正则表达式
123.35
可能不会达到您的预期,因为点与任何内容匹配。如果是这种情况,那么您可以使用
x in s
进行简单的字符串包含。You can use
re.search
instead ofre.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.If this is the case then you can do simple string containment using
x in s
.使用
re.search
或仅使用if l in temp:
注意:内置类型
list
不应被遮蔽,因此for l in strings:
> 更好Use
re.search
or just use inif l in temp:
Note: built-in type
list
should not be shadowed, sofor l in lists:
is better您可以使用
map
和any
进行稍微复杂的检查来完成此操作。我不确定这是否比编译的正则表达式更快。
You can do this with a slightly more complex check using
map
andany
.I'm not sure if this is faster than a compiled regexp.