Search code examples
pythonpython-3.xpython-re

Python- re.search() // Match start and end but do not include either in match result


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+


Solution

  • 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+