2

I am looking to find all strings between two substrings while keeping the first substring and discarding the second. The substrings might be one of several values though. For example, if these are the possible substrings:

subs = ['MIKE','WILL','TOM','DAVID']

I am looking to get the string between any of these like this:

Input:

text = 'MIKE an entry for mike WILL and here is wills text DAVID and this belongs to david'

Output:

[('MIKE': 'an entry for mike'),
 ('WILL': 'and here is wills text'),
 ('DAVID': 'and this belongs to david')]

Trailing spaces are not important. I have tried:

re.findall('(MIKE|WILL|TOM|DAVID)(.*?)(MIKE|WILL|TOM|DAVID)',text)

which only returns the first occurrence and retains the end substring. Not too sure of the best approach.

2 Answers 2

2

You may use

import re
text = 'MIKE an entry for mike WILL and here is wills text DAVID and this belongs to david'
subs = ['MIKE','WILL','TOM','DAVID']
res = re.findall(r'({0})\s*(.*?)(?=\s*(?:{0}|$))'.format("|".join(subs)), text)
print(res)
# => [('MIKE', 'an entry for mike'), ('WILL', 'and here is wills text'), ('DAVID', 'and this belongs to david')]

See the Python demo.

The pattern that is built dynamically will look like (MIKE|WILL|TOM|DAVID)\s*(.*?)(?=\s*(?:MIKE|WILL|TOM|DAVID|$)) in this case.

Details

  • (MIKE|WILL|TOM|DAVID) - Group 1 matching one of the alternatives substrings
  • \s* - 0+ whitespaces
  • (.*?) - Group 2 capturing any 0+ chars other than line break chars (use re.S flag to match any chars), as few as possible, up to the first...
  • (?=\s*(?:MIKE|WILL|TOM|DAVID|$)) - 0+ whitespaces followed with one of the substrings or end of string ($). These texts are not consumed, so, the regex engine still can get consequent matches.
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use the following regex to achieve your goal:

(MIKE.*)(?= WILL)|(WILL.*)(?= DAVID)|(DAVID.*)

It uses Positive lookahead to get the intermediate strings. (http://www.rexegg.com/regex-quickstart.html)

TESTED: https://regex101.com/r/ZSJJVG/1

Comments

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.