user2567325 user2567325 - 5 months ago 14
Python Question

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

I am new to Python and have been trying to find all the strings which match multiple patterns. I did some google search and found some posts which suggest to compile all the patterns into one. However they were using the

re.search()
function which only returns the first matched instance. I need to search all instances of strings which match any of the patterns in the order of their occurrence. Any direction/suggestion is welcome.

More specifically I am looking for something similar to this grep command

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

Answer

re.findall(combined_regex, your_string) is probably what you're looking for.

If you plan on doing this many times in the same program, consider compiling the regex as follows for better performance:

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