Skip to main content
 首页 » 编程设计

python之正则表达式 : How to name a group using match result

2024年08月19日43myhome

我想用匹配组的结果命名一个组。例如在 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:组名称“(?P=attr_name)”中的错误字符

请您参考如下方法:

您不能在正则表达式中动态分配组名。但是你可以这样做:

>>> 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'}