Reputation: 22282
I have a file that save lots of ip, and now I want to convert them like 127.0.0.1
to 127.0.0.0/24
use regex. I've tried something like this:
re.sub('\.*\n', '/24\n', f.read())
but it only add .0/24
after the ip(like convert 127.0.0.1
to 127.0.0.1.0/24
), and if I add a .
after \.
like this:
re.sub('\..*\n', '/24\n', f.read())
then 127.0.0.1
will be convert to 1/24
.
Upvotes: 0
Views: 137
Reputation: 5600
You can use a more detailed regex:
>>> ip='127.0.0.1'
>>> re.sub('([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)', r'\1.\2.\3.0/24', ip)
'127.0.0.0/24'
Upvotes: 1