如何在正则表达式标识的两个特定列表位置之间连接列表的元素(字符串)?

How to concatenate elements(strings) of a list, between two specific list positions as identified by a regex?

我有一长串元素(数千个),它们是字符串,需要捕获和连接正则表达式匹配的两个元素之间的字符串。

请参阅下面的代码,但是,我对如何捕获中间的文本并将每个元素连接成一个字符串感到困惑?


my_list = ['this is a test element 1', 'I need to capture after this element','capture1','capture2', 'capture3','.........', 'I need to capture before this element' ]
my_reg = re.compile(r'I need to capture.+')

captured_text=[]
for i,element in enumerate(my_list):
    m=my_reg.match(element)
    if m:
        captured_text.append(my_list[i+1])

但 i+1 超出范围

我希望最后得到一个字符串 capture1capture2capture3.....

match_indices = [i for i, s in enumerate(my_list) if my_reg.match(s)]
captured_text = my_list[min(match_indices)+1 : max(match_indices)]

结果:

>>> captured_text
['capture1', 'capture2', 'capture3', '.........']
>>> "".join(captured_text)
'capture1capture2capture3.........'