逗号拆分,不带引号

2024-05-11 14:33:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用正则表达式(re.split)拆分字符串,但我已经有一段时间没有使用正则表达式了。

字符串看起来像:

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

我想在每个逗号上拆分字符串,除非子字符串用引号括起来。

输出应该如下所示:

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

Tags: 字符串reoutputstringelement引号firstsplit
2条回答

你可以试试下面的代码

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

Regex从here:-)被盗

您希望使用csv模块,而不是重新创建它。

相关问题 更多 >