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

Time:11-15

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"?

CodePudding user response:

You can use a lookahead assertion:

re.findall(r'\bBut.*(?=\stypesetting\b)', res)
  • Related