0

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)
JonMorehouse
  • 1,313
  • 6
  • 14
  • 34

2 Answers2

1

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

Wooble
  • 87,717
  • 12
  • 108
  • 131
sshashank124
  • 31,495
  • 9
  • 67
  • 76
0

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')
Matt
  • 17,290
  • 7
  • 57
  • 71