Created
November 21, 2013 05:16
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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