import re # Input text input_text = """ object-group service service_group_proto_3 service-object object proto_3 object-group user DM_INLINE_USER_3 group-object user_group2 group-object test_user_group object-group user DM_INLINE_USER_4 group-object user_group_all user LOCAL\\ussss object-group user DM_INLINE_USER_5 group-object test_user_group group-object user_group2 object-group protocol nda group-object TCPUDP object-group service tcpudp tcp-udp group-object tcpudp_serv_group1 object-group network DM_INLINE_NETWORK_1 group-object net_group3 network-object object tetetet object-group protocol ip_proto_group protocol-object ip object-group protocol TTCCPPUUDDPP protocol-object udp protocol-object tcp object-group protocol DM_INLINE_PROTOCOL_2 protocol-object icmp protocol-object icmp6 object-group network U_NETWORK network-object host 10.1.46.10 network-object host 12.16.10.61 network-object host 100.60.4.2 object-group network ds_group_2 network-object ::/1 network-object host fc::ee network-object 1.2.3.0 255.255.255.0 network-object host 1.2.3.4 access-list OUTSIDE_access_in remark Test new description one """ def filter_necessary_data(text: str): result = [] lines = text.splitlines() i = 0 while i < len(lines): if lines[i].startswith("object-group network"): result.append(lines[i]) i += 1 while i < len(lines) and lines[i].startswith(" "): result.append(lines[i]) i += 1 else: i += 1 return result print(filter_necessary_data(input_text))