Skip to content

Instantly share code, notes, and snippets.

@asciimo
Created November 21, 2013 05:16
Show Gist options
  • Select an option

  • Save asciimo/7576426 to your computer and use it in GitHub Desktop.

Select an option

Save asciimo/7576426 to your computer and use it in GitHub Desktop.
Filtering a list of strings against a list of compiled regular expressions, in Python.
import re
patterns = [re.compile('one'), re.compile('two'), re.compile('three')]
strings = ['one', 'fudge', 'two', 'twenty', 'three', 'something']
# To collect the matches
[s for s in strings if any(p.match(s) for p in patterns)]
#Output: ['one', 'two', 'three']
# To colelct the non-matches
[s for s in strings if not any(p.match(s) for p in patterns)]
#Output: ['fudge', 'twenty', 'something']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment