1

The Exscript any_match() function uses regex to match patterns in strings and returns the results in a tuple.

I am attempting to match IP addresses in a traceroute output. It works for the most part, but for some reason returns some extra values (in addition to the targeted addresses). I would like some assistance in the correct regex to use that will return only the IP addresses without the extra values. **Note:**I have googled and searched stackoverflow for regex patterns as well as studied the regex help page. This is the closest regex that's worked so far.

def ios_commands(job, host, conn): conn.execute('terminal length 0') conn.execute('tr {}'.format(DesAddr)) print('The results of the traceroute', repr(conn.response)) for hops in any_match(conn,r'(([0-9]{1,3}\.){3}[0-9]{1,3})'): hop_addresses = list(hops) 

OUTPUT

the string being searched

hostname>('The results of the traceroute', "'tr 192.33.12.4\\r\\nType escape sequence to abort.\\r\\nTracing the route to hostname (192.33.12.4)\\r\\nVRF info: (vrf in name/id, vrf out name/id)\\r\\n 1 hostname (192.32.0.174) 0 msec 0 msec 0 msec\\r\\n 2 hostname (192.32.0.190) 0 msec 0 msec 0 msec\\r\\n 3 192.33.226.225 [MPLS: Label 55 Exp 0] 0 msec 4 msec 0 msec\\r\\n 4 192.33.226.237 0 msec 0 msec 0 msec\\r\\n 5 hostname (192.33.12.4) 4 msec * 0 msec\\r\\nhostname>'") 

['192.33.12.4', '12.'] #note the extra '12.' value ['192.33.12.4', '12.'] ['192.32.0.174', '0.'] ['192.32.0.190', '0.'] ['192.33.226.225', '226.'] ['192.33.226.237', '226.'] ['192.33.12.4', '12.'] 

1 Answer 1

3

You have 2 matching groups in your pattern. The first one (and outer one) is for the whole IP address; and the second group is repeated thrice:

([0-9]{1,3}\.){3} 

Use non-capturing groups:

((?:[0-9]{1,3}\.){3}[0-9]{1,3}) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.