Reputation: 4217
if I have a list ['default via 192.168.0.1 dev wlan0 proto static \n', '192.168.0.0/24 dev wlan0 proto kernel scope link src 192.168.0.11 \n']
what will be the most pythonic way to extract 192.168.0.1
and 192.168.0.11
out of it
Upvotes: 3
Views: 108
Reputation: 235984
Try this using regular expressions, where lst
is the list with the data:
import re
pat = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}[^/]')
[pat.search(s).group(0) for s in lst]
=> ['192.168.0.1', '192.168.0.11']
The above assumes that there's a valid IPv4 IP in each string in the list, and that after the IP there isn't a /
character.
Upvotes: 4
Reputation: 131
«Most pythonic» might be debatable, but something along these lines will work :
fct = lambda e : [w for w in e.split() if '.' in w and '/' not in w][0]
map( fct, l )
> ['192.168.0.1', '192.168.0.11']
Upvotes: 3