简体   繁体   English

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

[英]Regular expression: How to name a group using match result

I want to name a group using the result of matched group. 我想使用匹配组的结果来命名组。 For example in python: 例如在python中:

I want : 我想要 :

import re

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

I have tried: 我努力了:

import re

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

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

I get: 我得到:

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

You can't assign group names in the regex dynamically. 您不能在正则表达式中动态分配组名。 But you can do something like this: 但是您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM