KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
One of the biggest annoyances I find in Python is the inability of the re module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this: if re.match('foo (\w+) bar (\d+)', line): # do stuff with .group(1) and .group(2) elif re.match('baz whoo_(\d+)', line): # do stuff with .group(1) # etc. But unfortunately it's impossible to get to the matched object of the previous call to re.match , so this is written like this: m = re.match('foo (\w+) bar (\d+)', line) if m: # do stuff with m.group(1) and m.group(2) else: m = re.match('baz whoo_(\d+)', line) if m: # do stuff with m.group(1) Which is rather less convenient and gets really unwieldy as the list of elif s grows longer. A hackish solution would be to wrap the re.match and re.search in my own objects that keep state somewhere. Has anyone used this? Are you aware of semi-standard implementations (in large frameworks or something)? What other workarounds can you recommend? Or perhaps, am I just misusing the module and could achieve my needs in a cleaner way? Thanks in advance
Tags (comma-separated)
Save Edits
Cancel