squid22
squid22

Reputation: 33

Python regex to get values from keys:

I would like to get specific data values based on a match for a specific ID which is not sorted and could be anywhere in the line. Here is an example:

[ROUTE:10:23:191:271:3:81]
     route_protocol = ripv2
     dhcp_enabled = yes
     route_config = dynamic

How can I get the route_protocol value only for ROUTE IDs: 23 and 81?

Upvotes: 0

Views: 71

Answers (1)

syntaxError
syntaxError

Reputation: 866

This will return the values in a list in order of appearance.

with open('conftxt.txt') as config:
    l = [x for x in config.readlines() if 'route_config' in x]
    route_config_vals = [x.strip().split(' = ')[1] for x in l]

print(route_config_vals) #['dynamic']

EDIT

def extract_values(param: "str paramaeter to search for",
                   ) -> "dict:  ROUTE: param pairs":


  with open('conftxt.txt') as config:
        parameter_list = []

        # get list of parameters
        l = [x for x in config.readlines() if param in x]
        parameter_list= [x.strip().split(' = ')[1] for x in l]

        config.seek(0)  #back to top of file

        # get list of routes
        route_list = [x.strip() for x in config.readlines() if 'ROUTE' in x]
        pairs = {k: v for k, v in zip(route_list, parameter_list)}
        return pairs


print(extract_values('route_config'))  #{'[ROUTE:10:23:191:271:3:81]': dynamic'}
print(extract_values('dhcp_enabled'))  #{'[ROUTE:10:23:191:271:3:81]': 'yes'}

Upvotes: 1

Related Questions