这个问题已经多次被问及回答.一些例子:
[1],
[2].但似乎没有什么比较一般的东西.我正在寻找的是一种以逗号分隔字符串的方法,这些字符串不在引号或分隔符对中.例如:
s1 = 'obj<1, 2, 3>, x(4, 5), "msg, with comma"'
应该分为三个元素的列表
['obj<1, 2, 3>', 'x(4, 5)', '"msg, with comma"']
现在的问题是,这可能会变得更复杂,因为我们可以研究成对的<>和().
s2 = 'obj<1, sub<6, 7>, 3>, x(4, y(8, 9), 5), "msg, with comma"'
应分为:
['obj<1, sub<6, 7>, 3>', 'x(4, y(8, 9), 5)', '"msg, with comma"']
没有使用正则表达式的天真解决方案是通过查找字符来解析字符串,
更一般的功能是这样的:
def split_at(text, delimiter, exceptions):
"""Split text at the specified delimiter if the delimiter is not
within the exceptions"""
一些用途就是这样的:
split_at('obj<1, 2, 3>, x(4, 5), "msg, with comma"', ',', [(''), ('(', ')'), ('"', '"')]
正则表达式能够处理这个还是需要创建一个专门的解析器?