-3

I would extract all the numbers after a symbol contained in a output. Which is the better suited for the purpose, regular expressions ?

for eg i have an output as 172.4.5.3/32 and i need to filter this output as /32

syid
  • 5
  • 4

4 Answers4

2

In this particular case, I'd go with Python's classes designed for dealing with IP addresses:

from ipaddress import IPv4Network

n = IPv4Network('172.4.5.3/32')
print(n.prefixlen)
deceze
  • 510,633
  • 85
  • 743
  • 889
0

This splits the string into multiple strings (split where / occurs) and are put into an array. After this I select the last element of this array and prepend /.

input = "172.4.5.3/32"

output = '/' + input.split('/')[-1]

print(output)

output:

/32
tjallo
  • 781
  • 6
  • 25
0

You can split it on '/', or use re.findall.

re.findall('/.*', '172.4.5.3/32')[0]
outputs '/32'
rak1507
  • 392
  • 3
  • 6
  • Isn't it better to always grab the last element since `/*` will always be at the end of the string – tjallo Aug 04 '20 at 10:35
  • Oh yeah, fair point, could replace [0] with [-1] then, but seeing as there should only be 1, it doesn't really matter. – rak1507 Aug 04 '20 at 10:36
  • I agree with you that it probably doesn't happen. But better safe than sorry ;) – tjallo Aug 04 '20 at 11:03
0

The python .split() method allows you to split a string into multiple items of a list, splitting on a separator of your choice.

ip_string = '172.4.5.3/32'
ip_subnet = ip_string.split('/')[1]

will fetch you your second value of that split string, i.e. the '32'