Named groups for regex in Python
Regular expressions (regex) are still a bit of my Achilles’ heel in programming. I think they are super cool and useful, but I always have to rely heavily on cheatsheets, StackOverflow, and websites like Pythex to really get them to do what I want. Today was at least the third time in the past couple of weeks that I found myself searching for “named groups” and how exactly they work in Python. Of course, I ended up on the same StackOverflow question as always, and as all the times before, I was briefly confused because the code I wanted to copy is in the question, not in the accepted answer.1
I figured that maybe it is about time I just write down the correct syntax myself once, so that either my brain will now remember it, or that I at least know where to look it so.
So without further ado, here’s the example code for named group using Python’s re
module:
import re
test_string = 'alpha=1.4 beta=2 gamma=43 delta=None'
pattern = re.compile('beta=(?P<beta>\d+).*delta=(?P<delta>.+)')
matches = pattern.match(test_string)
if matches is not None:
beta = matches.group('beta')
delta = matches.group('delta')
Of course, technically, the re.compile()
is not really necessary, and you could also just do:
matches = re.match('beta=(?P<beta>\d+).*delta=(?P<delta>.+)', test_string)
-
I guess I have just been conditioned to assume that whatever code is in the question does not work, and that I should look at the answers to find the solution to my problem? ↩︎