2

I have a variable 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'''

I'm trying to split the string before the text Layer like below.

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'
]

2 Answers 2

6
import re
print re.split(r"\n(?=Layer)",x)

You can use lookahead with re here to achieve the same.

Output:

['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']

Or you can also use re.findall.

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

See Demo

Sign up to request clarification or add additional context in comments.

Comments

3

You need to use re.split

re.split(r'\s+(?=Layer:)', string)

This would do splitting on one or more space characters which exists just before to the string Layer:. And note that \s would match any kind of space character, ie vertical (newline,carrage return) as well as horizontal space character (whitespace,tabs).

Example:

>>> 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']

2 Comments

How can I achieve the same process using re.findall?
try re.findall(r'(?s).+?(?=\bLayer:|$)', string)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.