Using your code, returns
match_indices = [1, 6, 10]
captured_text = ['capture1', 'capture2', 'capture3', '.........', 'I need to capture **before** this element and separately after this element', 'captureA', 'captureB', 'captureC'] # all between 1 and 10
To capture groups between indices, you cannot use min()
and max()
. Instead iterate over each pair of adjacent indices in match_indices
. The captured_text
will return the list of lists.
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 and separately after this element',
'captureA',
'captureB',
'captureC',
'last capture ends before this element']
match_indices = [i for i, s in enumerate(my_list) if 'this element' in s]
captured_text = []
for i in range(1, len(match_indices)):
start = match_indices[i-1] + 1
end = match_indices[i]
captured_text.append(my_list[start:end])
print(captured_text)
# captured_text = [
# ['capture1', 'capture2', 'capture3', '.........'],
# ['captureA', 'captureB', 'captureC']
# ]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…