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,251
  • 3
  • 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
  • 84,802
  • 12
  • 102
  • 128
sshashank124
  • 29,826
  • 8
  • 62
  • 75
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
  • 16,540
  • 7
  • 55
  • 70