Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions one_line_regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,21 @@
import sys


def magic_match(pattern, target):
def magic_match(*args, **kwargs):
"""
Match a regex against a target string.

Assign the result to a 'match' variable in the *caller's scope*.
Assign the result to a 'match' variable in the *caller's global scope*.
"""
frame = sys._getframe(1)
result = re.match(pattern, target)
result = re.match(*args, **kwargs)
# This is properly, properly evil. Don't do this:
frame.f_locals['match'] = result
frame.f_globals['match'] = result
return result


if magic_match(r'[abcde]+', sys.argv[1]):
print 'Your match was %r' % match.group(0)
else:
print 'There was no match'
if __name__ == '__main__':
if magic_match(r'[abcde]+', sys.argv[1]):
print 'Your match was %r' % match.group(0)
else:
print 'There was no match'