My intention is to get all inbetween 'start' and 'end' variables. Currently struggling to understand how to apply the filters to get group excluding the start and end criteria.
start = 'melons'
end = 'strawberry'
s = 'banana apples melons cucumber strawberry grapes'
r = re.search('', s)
print(r.group(1))
#print = cucumber
CodePudding user response:
Can be achieved with below approach:
import re
start = 'melons'
end = 'strawberry'
s = 'banana apples melons cucumber strawberry grapes'
r = re.search(rf'{start}(.*?){end}', s)
print(r.group(1))
Output:
cucumber
CodePudding user response:
If you're starting off with Regex, then I recommend you use this tool. It's very useful and can help you write your own regex statements. It also will compile your statement to a language of your choice.
In the meantime, you can use a statement like melons(.*)strawberry
:
import re
regex = r"melons(.*)strawberry"
matches = re.search(regex, "banana apples melons cucumber strawberry grapes")
print(matches.groups()[0])
# cucumber