我有一个变量string
。
string = '''Layer:defaultRenderLayer
Line 1 text goes here
Line 2 text goes here
Line 3 text goes here
Layer:diffuse
Line 1 text goes here
Line 2 text goes here
Line 3 text goes here
Line 4 text goes here
Line 5 text goes here
Layer:outline
Line 1 text goes here
Line 2 text goes here'''
我正在尝试在文本Layer
之前拆分字符串,如下所示。
string_list = [
'Layer:defaultRenderLayer\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here',
'Layer:diffuse\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here\nLine 4 text goes here\nLine 5 text goes here',
'Layer:outline\nLine 1 text goes here\nLine 2 text goes here'
]
答案 0 :(得分:6)
import re
print re.split(r"\n(?=Layer)",x)
您可以在lookahead
使用re
来实现相同目标。
输出:
['Layer:defaultRenderLayer\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here',
'Layer:diffuse\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here\nLine 4 text goes here\nLine 5 text goes here',
'Layer:outline\nLine 1 text goes here\nLine 2 text goes here']
或者您也可以使用re.findall
。
print re.findall(r"\bLayer\b[\s\S]*?(?=\nLayer\b|$)",x
答案 1 :(得分:3)
您需要使用re.split
re.split(r'\s+(?=Layer:)', string)
这会将之前存在的一个或多个空格字符拆分为字符串Layer:
。请注意\s
将匹配任何类型的空格字符,即垂直(换行符,carrage return )以及水平空格字符(空格,制表符)。
示例:
>>> import re
>>> string = '''Layer:defaultRenderLayer
Line 1 text goes here
Line 2 text goes here
Line 3 text goes here
Layer:diffuse
Line 1 text goes here
Line 2 text goes here
Line 3 text goes here
Line 4 text goes here
Line 5 text goes here
Layer:outline
Line 1 text goes here
Line 2 text goes here'''
>>> re.split(r'\s+(?=Layer:)', string)
['Layer:defaultRenderLayer\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here', 'Layer:diffuse\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here\nLine 4 text goes here\nLine 5 text goes here', 'Layer:outline\nLine 1 text goes here\nLine 2 text goes here']