Reputation: 8554
I have a pool of ip addresses and I want to save them in a form of slash 24 prefix.
101.0.114.117|theavenueworkshop.com
10.2.0.95|storm8.com
10.2.0.96|prxy.net
10.2.0.99|fonality.com
10.2.0.9|rpb.ru
10.2.1.0|aiico.com
10.2.1.100|samasher.com
10.2.1.101|wps-inc.com
10.2.1.104|ufl.edu
10.2.0.6|waldorfford.com
10.2.0.71|inmobi.com
10.2.0.72|inmobi.com
10.2.0.75|amtrim.com
10.2.0.77|equifax.com
10.2.0.78|equifax.com
10.2.0.7|ppu.edu
10.2.0.83|enphg.com
10.2.0.86|3dna.io
10.2.0.87|nexica.com
so I want these to be converted to the following form (by replacing the last bit to zero and adding a slash 24 to the it):
101.0.114.0/24|theavenueworkshop.com
10.2.0.0/24|storm8.com
10.2.0.0/24|prxy.net
...
10.2.0.0/24|enphg.com
10.2.0.0/24|3dna.io
10.2.0.0/24|nexica.com
Can anybody help ?
Upvotes: 1
Views: 344
Reputation: 107287
you can use re.sub
and positive look-ahead:
>>> s="""101.0.114.117|theavenueworkshop.com
10.2.0.95|storm8.com
10.2.0.96|prxy.net
10.2.0.99|fonality.com
10.2.0.9|rpb.ru"""
>>> print re.sub(r'\d+(?=\|)',r'0/24',s)
101.0.114.0/24|theavenueworkshop.com
10.2.0.0/24|storm8.com
10.2.0.0/24|prxy.net
10.2.0.0/24|fonality.com
10.2.0.0/24|rpb.ru
if you want to split your string by |
you can do the following :
>>> l=[i.split('|')[0] for i in s.split('\n')]
>>> ['.'.join(i.split('.')[:3]+['0/24']) for i in l]
['101.0.114.0/24', '10.2.0.0/24', '10.2.0.0/24', '10.2.0.0/24', '10.2.0.0/24']
Upvotes: 3
Reputation: 2419
You can use re.sub() with pattern \.[0-9]*[|]
to find the text that need to be replaced by the text .0/24|
line = '101.0.114.117|theavenueworkshop.com'
print re.sub("\.[0-9]*[|]",'.0/24|', line)
#101.0.114.0/24|theavenueworkshop.com
Upvotes: 1