Python: regex parse text to create dict -


i have problem 1 task:

i have output cisco hw.

ip access list 100           10 permit igmp any           20 deny any   ip access list 200           10 permit ip 192.168.1.1/32            20 permit ip 192.168.2.1/32           30 permit ip 192.168.3.3/32           40 deny any 

the task make dict access list number key , access list rule number value.

acl_dict = {'100' : '10', '100' : '20','200': '10', '200': '20', '200': '30', '200': '40'} 

i have written regex:

rx = re.compile("""                    list\s(.*)[\n\r]                    \s{4}(\d{1,3}).+$                  """,re.multiline|re.verbose)          match in rx.finditer(text):              print (match.group(1))              print (match.group(2)) 

but shows number first 2 strings (100 , 10) need modify somehow regex match numbers make needed dict. can ?

it's possible single method using newest regex module:

import regex  text = """ ip access list 100       10 permit igmp any       20 deny any   ip access list 200       10 permit ip 192.168.1.1/32        20 permit ip 192.168.2.1/32       30 permit ip 192.168.3.3/32       40 deny any """  acl_dict = {} rx = regex.compile("list\s(.+)[\n\r](\s{4}(\d{1,3}).+[\n\r])*", regex.multiline|regex.verbose) match in rx.finditer(text):     acl_dict[match.group(1)] = match.captures(3)  print(acl_dict) 

output:

$ python3 match.py  {'200  ': ['10', '20', '30', '40'], '100  ': ['10', '20']} 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -