如何在Python中拆分此字符串?

sre*_*rai 2 python

我有一个变量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'''
Run Code Online (Sandbox Code Playgroud)

我试图在文本之前分割字符串,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'
]
Run Code Online (Sandbox Code Playgroud)

vks*_*vks 6

import re
print re.split(r"\n(?=Layer)",x)
Run Code Online (Sandbox Code Playgroud)

你可以用lookaheadre这里来达到相同.

输出:

['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']
Run Code Online (Sandbox Code Playgroud)

或者你也可以使用re.findall.

print re.findall(r"\bLayer\b[\s\S]*?(?=\nLayer\b|$)",x
Run Code Online (Sandbox Code Playgroud)

见演示