【发布时间】:2013-06-07 15:04:15
【问题描述】:
这应该是使用re 库的一项非常简单的任务。但是,我似乎无法在分隔符 ] 和 [ 处拆分我的字符串。
我已经阅读了Splitting a string with multiple delimiters in Python、Python: Split string with multiple delimiters 和Python: How to get multiple elements inside square brackets。
我的字符串:
data = "This is a string spanning over multiple lines.
At somepoint there will be square brackets.
[like this]
And then maybe some more text.
[And another text in square brackets]"
它应该返回:
['This is a string spanning over multiple lines.\nAt somepoint there will be square brackets.','like this', 'And then maybe some more text.', 'And another text in square brackets']
一个简短的例子:
data2 = 'A new string. [with brackets] another line [and a bracket]'
我试过了:
re.split(r'(\[|\])', data2)
re.split(r'([|])', data2)
但是那些会导致在我的结果列表中包含分隔符或完全错误的列表:
['A new string. ', '[', 'with brackets', ']', ' another line ', '[', 'and a bracket', ']', '']
结果应该是:
['A new string.', 'with brackets', 'another line', 'and a bracket']
作为一项特殊要求,应删除分隔符前后的所有换行符和空格,也不应包含在列表中。
【问题讨论】: