2013-06-11 73 views
2

使用re库这应该是一项非常简单的任务。但是,我似乎无法将我的字符串拆分为分号][在列表中没有分隔符的多个分隔符处分割

我已经阅读Splitting a string with multiple delimiters in PythonPython: Split string with multiple delimitersPython: 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', ']', ''] 

结果应该是并且在分隔符应该被移除并且不被包括在列表中。

回答

7
​​
+1

是的,这比我推荐的非捕获组更简单。 –

+1

工程很好。就像一个补充:我如何删除元素结尾/开始处的所有换行符和空格? – cherrun

+0

好的。弄清楚了。在列表中的每个元素上使用'strip()'。再次感谢。 – cherrun

4

正如arshajii指出的那样,这个特定的正则表达式根本不需要组。

如果确实需要组来表示更复杂的正则表达式,则可以使用非捕获组来分割而不捕获分隔符。这对其他情况可能有用,但在这里语法混乱矫枉过正。

(?:...)

A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern. 

http://docs.python.org/2/library/re.html

所以这里的不必要的复杂性,但示范的例子是:

re.split(r'(?:\[|\])', data2) 
2

用这个代替(无捕获组):

re.split(r'\s*\[|]\s*', data) 

或较短:

re.split(r'\s*[][]\s*', data) 
0

Couuld无论是拆分或的findall所有,如:

data2 = 'A new string. [with brackets] another line [and a bracket]' 

采用分体式滤除前/后间隔:

import re 
print filter(None, re.split(r'\s*[\[\]]\s*', data2)) 
# ['A new string.', 'with brackets', 'another line', 'and a bracket'] 

或者可能适应的findall方法:

print re.findall(r'[^\b\[\]]+', data2) 
# ['A new string. ', 'with brackets', ' another line ', 'and a bracket'] # needs a little work on leading/trailing stuff...