Python匹配组

Python匹配组,python,regex,string,string-matching,Python,Regex,String,String Matching,使用python创建匹配组以从字符串中提取两个值时遇到问题 以下是我的意见: # SomeKey: Value Is A String 我希望能够使用python match group/regex语句提取SomeKey,并且值是一个字符串。这是我到目前为止所拥有的 import re line = "# SomeKey: Value Is A String" mg = re.match(r"# <key>: <value>", line) 重新导入 line=“#S

使用python创建匹配组以从字符串中提取两个值时遇到问题

以下是我的意见:

# SomeKey: Value Is A String
我希望能够使用python match group/regex语句提取
SomeKey
,并且
值是一个字符串。这是我到目前为止所拥有的

import re
line = "# SomeKey: Value Is A String"
mg = re.match(r"# <key>: <value>", line)
重新导入
line=“#SomeKey:Value是字符串”
mg=重新匹配(r“#:”,第行)

您必须提供匹配的字符串:

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
或者,要自动获取键和值的元组,可以执行以下操作:

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

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

对于名称,您可以执行以下操作:

mg = re.match(r"# (?P<key>[^:]+): (?P<value>.*)", line)
print mg.group('key')
mg=re.match(r“#”(?P[^::]+):(?P.*),行)
打印管理组(“键”)

除非您的实际用例更加复杂,否则您可以使用
findall
直接将值解压缩到相应的变量中,如下所示:

import re
line = "# SomeKey: Value Is A String"
key, val = re.findall(r"# (.*?): (.*)$", line)[0]
# (key, val) == ('SomeKey', 'Value Is A String')

我把问题打错了。谢谢你的快速回答我如何使用命名组?它类似于()Ibelieve@JonMorehouse,你是什么意思。与此同时,我已经更新了我的答案again@JonMorehouse,答案更新为包含命名组。