按未被引号包围的逗号分割

-3 投票
2 回答
8444 浏览
提问于 2025-04-18 18:32

我想用正则表达式来分割一个字符串(用re.split),不过我已经有一段时间没用过正则表达式了。

这个字符串看起来是这样的:

string = '"first, element", second element, third element, "fourth, element", fifth element'

我想在每个逗号处分割这个字符串,但如果某个子串被引号包住,就不分割。

输出结果应该是这样的:

output = ['"first, element"', 'second element', 'third element', '"fourth, element"', 'fifth element']

2 个回答

5

你想用 csv 这个模块,而不是自己重新发明一个。

3

你可以试试下面的代码,

>>> import re
>>> string = '"first, element", second element, third element, "fourth, element", fifth element'
>>> m = re.split(r', (?=(?:"[^"]*?(?: [^"]*)*))|, (?=[^",]+(?:,|$))', string)
>>> m
['"first, element"', 'second element', 'third element, "fourth, element"', 'fifth element']

这个正则表达式是从 这里 偷来的 :-)

撰写回答