Question

I'm having trouble creating a match group to extract two values from a string using python

Here's my input:

# SomeKey: Value Is A String

And I'd like to be able to extract SomeKey and Value Is A String using a python match group / regex statement. Here's what I have so far

import re
line = "# SomeKey: Value Is A String"
mg = re.match(r"# <key>: <value>", line)
Was it helpful?

Solution

You have to provide the string you're matching:

import re
line = "# SomeKey: Value Is A String"
mg = re.match(r"# ([^:]+): (.*)", line)

>>> print mg.group(1)
SomeKey
>>> print mg.group(2)
Value Is A String

Or to automatically get a tuple of key and value, you can do:

import re
line = "# SomeKey: Value Is A String"
mg = re.findall(r"# ([^:]+): (.*)", line)

>>> print mg
[('SomeKey', 'Value Is A String')]

DEMO

For names, you would do:

mg = re.match(r"# (?P<key>[^:]+): (?P<value>.*)", line)
print mg.group('key')

DEMO

OTHER TIPS

Unless your real use-case is way more complicated, you can directly unpack the values into the corresponding variables by using findall like this:

import re
line = "# SomeKey: Value Is A String"
key, val = re.findall(r"# (.*?): (.*)$", line)[0]
# (key, val) == ('SomeKey', 'Value Is A String')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top