在 Python 中捕获重复组

capturing a repeated group in Python

我想捕获 n 次一个重复自身 n 次的模式,n >= 0。我有这样的字符串:

a = 'x="2"'
b = 'x="2,3", y="hello", z="true"'

我想提取 'x' 及其值 '2,3'、'y' 及其值 'hello' 等。变量之间用逗号分隔,后跟space;值在双引号内。

如何使用 Python 中的 re 库执行此操作?

我天真地尝试了以下内容:

match = re.search(r'^((?P<variable>[0-9a-zA-Z_-]+)="(?P<value>.*)"(?:,\s)?)*', b)

如果我打印 match.groupdict(),它会输出:

{'variable': 'x', 'value': '2,3", y="hello", z="true'}

你得到的比你预想的多的原因是你匹配(删除了组命名):

".*"

由于正则表达式默认使用贪婪匹配,它会尽可能多地获取文本,只要它可以在末尾添加 ",即使中间文本也包含 ".您可以将其设为非贪婪匹配:

"(?P<value>.*?)"

或者贪婪匹配非"字符:

"(?P<value>[^"]*)"

下一个问题是您会发现这只匹配字符串中最后一次出现的模式。如果您想获得所有未知数量的匹配项,您需要 re.findall(). Unfortunately, findall() doesn't support groupdict. Its cousin re.finditer(),但是,returns 匹配具有以下方法的对象:

for match in re.finditer(r'(?P<variable>[0-9a-zA-Z_-]+)="(?P<value>[^"]*)"', b):
    print(match.groupdict())

{'variable': 'x', 'value': '2,3'}
{'variable': 'y', 'value': 'hello'}
{'variable': 'z', 'value': 'true'}
import re

a = 'x="2"'
b = 'x="2,3", y="hello", z="true"'

p = '(\w+)=\"([^\"]*)\"'

ms = re.findall(p, b)
print ms
ms = re.findall(p, a)
print ms

输出:

D:\>python reg.py
[('x', '2,3'), ('y', 'hello'), ('z', 'true')]
[('x', '2')]

D:\>

你可以在一行中尝试 Positive Lookbehind

import re
pattern=r'(?<=((\w)=))"(.*?)"'
string="""'x="2,3", y="hello", z="true"'"""

print([(i.group(2),i.group(3)) for i in re.finditer(pattern,string)])

输出:

[('x', '2,3'), ('y', 'hello'), ('z', 'true')]