Lab 2 of 5
Β·
Semi-Guided
Parse Hostname Components with re
Objective: Use a regular expression with named groups to extract device type, role, and number from hostnames.
Instructions
Create a file called lab2.py. Write a function called parse_hostname(hostname) that uses re.match() with named groups to extract three parts from a hostname in the format <type>-<role>-<num>:
type:sw,rtr, orfwrole: one or more word charactersnum: one or more digits
Test it against these hostnames:
hostnames = ["sw-core-01", "rtr-edge-01", "fw-dmz-02", "ap-wifi-03"]
If the pattern does not match, print <hostname>: no match.
Your output must match exactly:
sw-core-01 type=sw role=core num=01
rtr-edge-01 type=rtr role=edge num=01
fw-dmz-02 type=fw role=dmz num=02
ap-wifi-03: no match
Run it with python3 lab2.py. Paste your output below and submit.
π‘ Show Hint
Pattern: r"^(?P<type>sw|rtr|fw)-(?P<role>\w+)-(?P<num>\d+)$". Use match.group("type"), match.group("role"), match.group("num"). f-string with column alignment: f"{hostname:<14} type={m.group('type'):<5} role={m.group('role'):<6} num={m.group('num')}"
Paste Your Output