user10561801
user10561801

Reputation:

need to split the string based on the keyword

string = """Hello World A \n Block1 \n Block2 \n \n Hello World B \n Block1 \n Block2"""

I want to split the string into two parts using regular expression in python, in which the first part should Contain the block Hello World A till Hello World B and the second part should contain the block from Hello World B till the end of the string.

I tried re.findall() , but that didn't fetch me expected results. I want to know which regular expression statement can be used in this?

Upvotes: 0

Views: 48

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521864

We can try using re.findall in DOT ALL mode:

string = "Hello World A \n Block1 \n Block2 \n \n Hello World B \n Block1 \n Block2"
result = re.findall("Hello World.*?(?=Hello World|$)", string, re.DOTALL)
print(result)

['Hello World A \n Block1 \n Block2 \n \n ', 'Hello World B \n Block1 \n Block2']

Here is the pattern I used:

Hello World.*?(?=Hello World|$)

This matches Hello World, followed by anything provided that we don't consume another Hello World, or the very end of the string. DOT ALL mode is necessary because we want .* to be able to match and consume across newlines.

Upvotes: 1

Related Questions