正则表达式:如何使用匹配结果命名组

时间:2017-11-01 07:52:50

标签: python regex

我想使用匹配组的结果命名一个组。例如在python中:

我想:

import re

match = re.search(WHAT_I_NEED, 'name = tom')
assert match.groupdict()['name'] == 'tom'
if match.groupdict() == {'name': 'tom'}:
    print('better')

我尝试过:

import re

WHAT_I_NEED = r'(?P<attr_name>\w+) = (?P<(?P=attr_name)>\w+)'

match = re.search(WHAT_I_NEED, 'name = tom')

我明白了:

sre_constants.error: bad character in group name '(?P=attr_name)'

1 个答案:

答案 0 :(得分:3)

您无法动态分配正则表达式中的组名。但你可以这样做:

>>> data = "name = tom, age = 12, language = Python"
>>> regex = re.compile(r"(?P<key>\w+) = (?P<value>\w+)")
>>> matches = {k: v for k,v in regex.findall(data)}
>>> matches
{'age': '12', 'language': 'Python', 'name': 'tom'}