Remi Guan
Remi Guan

Reputation: 22282

How to convert ip like `127.0.0.1` to `127.0.0.0/24` use regex?

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

Answers (2)

ahmed
ahmed

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

hjpotter92
hjpotter92

Reputation: 80639

re.sub(r'\.\d+($|\n)', '.0/24\n', f.read())

Upvotes: 2

Related Questions