Created
February 11, 2017 15:58
-
-
Save 23maverick23/28dd50429855bdfb43118178d29dccb9 to your computer and use it in GitHub Desktop.
Python: Regexp in list comprehension (shortcut syntax)
This file contains 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
# Taken from Stack Overflow answer http://stackoverflow.com/a/2436623/4093021 | |
import re | |
# items = ['[1] rymoio [rymoio 7s] foo bar', '[2] baz [rymoio 2d] hello world'] | |
# assign matches to callable group parameters | |
regex = r"(?P<who>.*\[.*\]\s)(?P<what>.*)" | |
# bound method outside of the listcomp optimization | |
src = re.search | |
# assign matches to m within listcomp | |
items = [[m.group('who'), m.group('what')] for item in items for m in [src(regex, item)] if m] | |
# >>> [['[1] rymoio [rymoio 7s] ', 'foo bar'], ['[2] baz [rymoio 2d] ', 'hello world']] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment