Home > database >  Find all the in between using regex and python
Find all the in between using regex and python

Time:07-13

I want to get all of the string in between the "and" and end at the "or". How would you do this in python using regex and store into a tuple. We don't know the size of the actual sentence and the sentences can have as many AND's but only one ending OR.

So:

A and B and C and D or E

Would become:

tuple = (A,B,C,D)

CodePudding user response:

This seems to work. It returns a list, not a tuple, though.

import re
s = input()
print(re.findall(r'([^\s] ) (?:and|or)', s))

CodePudding user response:

import re
st = "A and B and C and D or E"
tp=tuple([x.strip() for x in  re.split(r"and|or",st)])
print(tp)

Output:

('A', 'B', 'C', 'D', 'E')
  • Related