Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式:如何使用匹配结果命名组_Python_Regex - Fatal编程技术网

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

Python 正则表达式:如何使用匹配结果命名组,python,regex,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+) = (?

我想使用匹配组的结果命名一个组。例如,在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')
我试过:

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')
重新导入
需要什么=r'(?P\w+)=(?P\w+)
匹配=重新搜索(我需要什么,'name=tom')
我得到:


sre_常量。错误:组名“(?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'}
data=“name=tom,age=12,language=Python” >>>regex=re.compile(r“(?P\w+)=(?P\w+) >>>匹配={k:v代表k,在regex.findall(数据)中为v} >>>火柴 {'age':'12','language':'Python','name':'tom'}
你不能那样做看起来像是一个-你想在这里实现什么?