![](/img/trans.png)
[英]Is there a way to check for two different patterns in the same string in regex python?
[英]simpler way to check if two different strings are in a third string in python
这是我下面的代码,可以正常工作。 'cluster_name'
是一个字符串变量,将保留一些文本。
if 'abc' not in cluster_name or 'xyz' not in cluster_name:
print "true"
else:
print "false"
我一直在寻找使if
条件更加简单的方法,例如:
if 'abc' or 'xyz' not in cluster_name:
print "true"
else:
print "false"
有没有更简单的方法可以做到这一点?
您的方法看起来不错,但不能很好地泛化(假设您必须检查十个子字符串而不是两个)。 尝试any
。
substrings = ['abc', 'xyz']
if any(substr not in cluster_name for substr in substrings):
print("true")
else:
print("false")
import re
print (re.search('abc|xyz',cluster_name) is not None)
更简单。 它并不需要if
还是else
; 您可以根据需要延长搜索字符串(尽管在合理范围内,毫无疑问)。 re.search
返回None
如果正则表达式不匹配,你想的是倒数,因此not None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.