Vvarner
Vvarner

Reputation: 13

Regex that makes IPV6 addresses shorter

For example, i have a dozen of IPV6 addresses, with 8 parts which are seperated by ":". If the first few characters are null in these parts then i wanna remove them with a simple regex.

Input:

1034:0123:0000:2100:3120:0000:0022:0001

Output:

1034:123::2100:3120::22:1

Is it possible?

Upvotes: 1

Views: 699

Answers (2)

AndrewTet
AndrewTet

Reputation: 1182

Talked about it in the comments, but it works now so here's the answer.

/(^|:)0{1,4}/g

That regex should work.

Upvotes: 1

linuxfan
linuxfan

Reputation: 1160

You can use python's socket module to get

>>> socket.getaddrinfo('1034:0123:0000:2100:3120:0000:0022:0001', 0, socket.AF_INET6)
[(10, 1, 6, '', ('1034:123:0:2100:3120:0:22:1', 0, 0, 0)), (10, 2, 17, '', ('1034:123:0:2100:3120:0:22:1', 0, 0, 0)), (10, 3, 0, '', ('1034:123:0:2100:3120:0:22:1', 0, 0, 0))]

>>> socket.getaddrinfo('1034:0123:0000:2100:3120:0000:0022:0001', 0, socket.AF_INET6)[0][4][0]
'1034:123:0:2100:3120:0:22:1'

As you can see, the resulting IPv6 address has all the excess zeroes stripped out.

Upvotes: 1

Related Questions