python - Regular expression to match with optional following text -


i'm new regular expressions , need finding correct regular expression.

i have text file of form:

apple 4 bananas 5 bananas 5 7 apple 3 apple 6 bananas 3 bananas 4 5 apple 3 bananas 9  

i looking regular expression match last occurrence of "bananas.*" after each "apple.*", keeping in mind every "apple.*" there may no "bananas.*". regex should match following:

bananas 5 7  bananas 4 5 bananas 9 

thanks in advance. doing in python if helps.

it is possible regular expressions:

^apple.+[\n\r] (?:(bananas.*)[\n\r]?)+ 

see a demo on regex101.com, mind different modifiers , use group 1 of every match.


full python code:

import re  string = """ apple 4 bananas 5 bananas 5 7 apple 3 apple 6 bananas 3 bananas 4 5 apple 3 bananas 9  """  rx = re.compile(r"""         ^apple.+[\n\r]         (?:(bananas.*)[\n\r]?)+         """, re.multiline | re.verbose)  bananas = [m.group(1) m in rx.finditer(string)] print(bananas) 

see a demo on ideone.com.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -