Python:如何找到与给定的多个模式中的任何一个匹配的所有字符串

Python: How can I find all strings matching any of the multiple patterns given

我是 Python 的新手,一直在尝试查找与多个模式匹配的所有字符串。我做了一些 google 搜索并找到了一些建议将所有模式编译为一个的帖子。但是他们使用的 re.search() 函数只 returns 第一个匹配的实例。我需要按出现顺序搜索与任何模式匹配的所有字符串实例。欢迎任何 direction/suggestion。

更具体地说,我正在寻找类似于此 grep 命令的东西

grep -i "[0-9' '-:A-Za-z].* ERROR.*Job failed\|Caused by:\|^      *at\|ERROR\|more$" <file-name>

re.findall(combined_regex, your_string) 可能就是您要找的。

如果您计划在同一程序中多次执行此操作,请考虑按如下方式编译正则表达式以获得更好的性能:

compiled = re.compile(combined_regex)
results = compiled.findall(your_string)

如果我没理解错的话,你正在寻找这样的东西:

import re

l_string="""gfrwrfr
gerqgeq
ERROR gferagqe
hello ERROR
smth more
more smth
Caused by: gferg
"""

pattern_strings =['[0-9" "-:A-Za-z].*ERROR.*Job run failed', 'Caused by:','^ *at','ERROR','more$']
pattern_string = '|'.join(pattern_strings)
pattern = re.compile(pattern_string)

for line in l_string.split("\n"):
    result = pattern.search(line)
    if result:
        print result.string

但是当然,因为我们已经在行循环中,所以我们可以打印行而不是 match_obj.string。

程序输出:

$  ./multiple_re.py
ERROR gferagqe
hello ERROR
smth more
Caused by: gferg

使用multi_pattern_search。示例如下。

from multi_pattern_search import MultiPatternSearch

search = MultiPatternSearch()

search.add_keyword("foo")
search.add_keyword("bar")

print search.exist("apple tree foo john doe")

for k, v in search.count("apple tree foo bar foobar john doe").iteritems():
    print k, v