处理多个组的正则表达式形成一个可能以逗号分隔的列表

Regex handling multiple groups form a potentially comma delimited list

我正在尝试通过正则表达式解析每个元素中包含多个捕获组的逗号分隔列表。

示例文本

col1 = 'Test String' , col2= 'Next Test String',col3='Last Text String', col4=37

我试过使用这个正则表达式的各种变体

(.*?)\s?=\s?(.*?)\s?,?

但它从来没有给我想要的东西,或者如果它接近它就无法处理只有一个元素,反之亦然。

我期待的是包含 3 个组的比赛列表

Match1 group 0 the whole match
Match1 group 1 col1
Match1 group 2 'Test String'
Match2 group 0 the whole match
Match2 group 1 col2
Match2 group 2 'Next Test String'
Match3 group 0 the whole match
Match3 group 1 col3
Match3 group 2 'Last Test String'
Match4 group 0 the whole match
Match4 group 1 col4
Match4 group 2 37

(注意我只对第 1 组和第 2 组感兴趣)

我故意让这个非语言特定,因为我无法让它在在线 Regex 调试器中工作,但是,我的目标语言是 Python 3

提前谢谢你,我希望我已经说清楚了

(.*?)\s?=\s?(.*?)\s?,? 正则表达式只有一个强制模式,=。开头的 (.*?) 扩展到最左边的 = 并且该组捕获最左边的任何文本 = 和它后面的可选空格。其余的子模式可以不匹配,有空格也匹配\s?,有两个也匹配,有逗号也匹配and消费,.*? 部分被简单地跳过,因为它是懒惰的。

如果你想得到包含单引号的第二个捕获组,你可以使用

(?:,|^)\s*([^\s=]+)\s*=\s*('[^']*'|\S+)

参见 this regex pattern。它匹配

  • (?:,|^) - 匹配 , 或字符串开头的非捕获组
  • \s* - 零个或多个空格
  • ([^\s=]+) - 第 1 组:除空格和 =
  • 之外的一个或多个字符
  • \s*=\s* - = 包含零个或多个空格的字符
  • ('[^']*'|\S+) - 第 2 组:'、零个或多个非 ' 和一个 ',或一个或多个非空白。

如果你想排除单引号,你可以post-处理匹配,或者在'([^']*)'中使用额外的捕获组,然后检查该组是否匹配:

import re
text = "col1 = 'Test String' , col2= 'Next Test String',col3='Last Text String', col4=37"
pattern = r"([^,\s=]+)\s*=\s*(?:'([^']*)'|(\S+))"
matches = re.findall(pattern, text)
print( dict([(x, z or y) for x,y,z in matches]) )
# => {'col1': 'Test String', 'col2': 'Next Test String', 'col3': 'Last Text String', 'col4': '37'}

参见 this Python demo

如果你想用纯正则表达式来做到这一点,你可以使用 branch reset group:

import regex  # pip install regex
text = "col1 = 'Test String' , col2= 'Next Test String',col3='Last Text String', col4=37"
print( dict(regex.findall(r"([^,\s=]+)\s*=\s*(?|'([^']*)'|(\S+))", text)) )

参见 Python demo (regex demo)。