Split string by starting at one keyword and stopping at the word preceding another

Question:

I have a set of strings I want to loop through that are all different but can be broken up using the same keywords. This will extract substrings that all start and stop at the same words but will have different values in them. Take the following string:

res = "But also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop"

To extract the string: "But also the leap into electronic"
I can use:

first_line = re.findall('But.*electronic', res)

But the word ‘electronic’ will change in each string and ‘typesetting’ will remain constant. How can I extract the text starting with ‘But’ and ends at the word before "typesetting"?

Asked By: Munrock

||

Answers:

You can use a lookahead assertion:

re.findall(r'bBut.*(?=stypesettingb)', res)
Answered By: blhsing
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.