Python- re.search() // 匹配开始和结束但不包含在匹配结果中

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

我的意图是让所有变量都介于 'start' 和 'end' 之间。 目前正在努力了解如何应用过滤器来获取不包括开始和结束条件的组。

start = 'melons'
end = 'strawberry'
s = 'banana apples melons+cucumber+strawberry grapes'

r = re.search('', s)

print(r.group(1)) 
#print = +cucumber+

可以通过以下方法实现:

import re
start = 'melons'
end = 'strawberry'
s = 'banana apples melons+cucumber+strawberry grapes'

r = re.search(rf'{start}(.*?){end}', s)

print(r.group(1)) 

输出:

+cucumber+

如果您刚开始使用正则表达式,那么我建议您使用 this 工具。它非常有用,可以帮助您编写自己的正则表达式语句。它还会将您的语句编译成您选择的语言。

在此期间,您可以使用 melons(.*)strawberry:

这样的语句
import re

regex = r"melons(.*)strawberry"

matches = re.search(regex, "banana apples melons+cucumber+strawberry grapes")

print(matches.groups()[0])
# +cucumber+