Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a lookahead assertion:

re.findall(r'\bBut.*(?=\stypesetting\b)', res)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading