检查所有列表项是否存在于一行中(正则表达式)



我知道正则表达式中的OR条件是"|"例如

re.search(r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)", line):

查找一行是否包含对月份的引用。

如果我们希望所有的项都存在于一行(或str)中呢?现在是这样的

    if re.search(r"ERRO", line) and re.search(r"MainThread:", line):

,但我可能想要添加更多的条件。此外,如果这些元素存在于列表中,而我们不想遍历该列表,该怎么办?有什么蟒式的方法吗?

谢谢

使用all,它将惰性求值。

conditions = ["foo","bar"]
s = "foo bar"
print all(x in s.split()  for x in conditions)
True
l = ["fo","bar"]
s = "foo bar"
print all(x in s.split() for x in conditions)
False

如果你不拆分单词,像fo这样的单词将被认为在一行中,因此拆分或不拆分取决于你认为在行的内容:

conditions = ["fo","bar"]
s = "foo bar"
print all(x in s  for x in conditions)
True

and条件在regexp语言中用头查找表示:

import re
print re.search(r'^(?=.*foo)(?=.*baz)(?=.*bar)', "foo and bar and baz")   # ok
print re.search(r'^(?=.*foo)(?=.*baz)(?=.*bar)', "foo and bar and spam")  # nope

如果你有一个关键字列表,你可以动态地创建这个正则表达式

keywords = 'foo', 'bar', 'baz'
regex = '^' + ''.join("(?=.*%s)" % s for s in keywords)

当然,如果您只寻找文字字符串,all(word in string for word in words)会更简单(不一定更快)。

可以使用Python的in运算符:

if "ERRO" in line and "MainThread:" in line:

如果您将关键字保存在列表中,则使用all函数检查它们:

keywords = ["ERRO", "MainThread", ...]    
if all(k in line for k in keywords):

最新更新