将捕获组转换为命名捕获组

Convert capture group to named capture group

如果我将名称作为列表提供,我将如何将简单的捕获组转换为命名的捕获组,我通常使用 python 编程,但对可能有助于实现此目的的其他语言开放。

基本示例:

正则表达式:

(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s(\w+)\s(\w+)\s(\d+)

姓名:

["ip","name","proto","http_status_code"]

最终结果正则表达式:

(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s(?<name>\w+)\s(?<proto>\w+)\s(?<http_status_code>\d+)

regex_data_to_test:

"172.16.1.1 bob tcp 200"

谢谢!

您需要在每个组中添加P,即:

(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s
(?P<name>\w+)\s
(?P<proto>\w+)\s
(?P<http_status_code>\d+)

Python 这可能是

import re

rx = re.compile(r'(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s(?P<name>\w+)\s(?P<proto>\w+)\s(?P<http_status_code>\d+)')

string = "172.16.1.1 bob tcp 200"

for m in rx.finditer(string):
    print(m.groupdict())

产生

{'ip': '172.16.1.1', 'name': 'bob', 'proto': 'tcp', 'http_status_code': '200'}

regex101.com 上查看您的表达式演示。


请注意,如果您始终使用此格式,则可以轻松拆分和解压缩:
string = "172.16.1.1 bob tcp 200"
ip, name, proto, status = string.split()

print(ip)

您可以使用以下内容,但如果您有嵌套括号,它会变得非常棘手:

reg = r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s(\w+)\s(\w+)\s(\d+)"
groupNames = ["ip","name", "proto", "http_status_code"]

splitReg = [a for a in reg.split("(") if a] # skip empty groups
if len(groupNames) == len(splitReg):
    newReg = ''.join([("(?P<" + name + ">" + val) 
        for name, val in zip(groupNames, splitReg)])
    print(newReg)

输出:

(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s(?P<name>\w+)\s(?P<proto>\w+)\s(?P<http_status_code>\d+)