简体   繁体   中英

Python - remove leading zeros from IP addresses

I am trying to remove leading zeros from IP addresses but it's not working

import re

def remove_zeros_from_ip(ip_add):
  string = re.sub('(?!(\.0\.))(\.[0]{1,2})', '.', ip_add)  
  return string

ip = '10.0.01.10'
print(remove_zeros_from_ip(ip))

ip1 = '10.00.002.20'
print(remove_zeros_from_ip(ip1))

but getting this-

10.0.1.10
10..2.20

How to get?-

10.0.1.10
10.0.2.20

You can split the IP octets and then convert Octets in string to int, and then back to str.

>>> ip='10.00.01.10'
>>> '.'.join([str(int(x)) for x in ip.split('.')])
'10.0.1.10'

You can remove the zeros that are preceded by a . or ^ (start of line) and followed by anything other than a . with what preceded it ( . or start of line):

import re

def remove_zeros_from_ip(ip_adr):
  return re.sub('(^|\.)0+(?=[^.])', r'\1', ip_adr)

Test:

print(remove_zeros_from_ip('10.0.01.10'))

print(remove_zeros_from_ip('10.00.002.20'))

print(remove_zeros_from_ip('0010.00.02.0020'))

Output:

10.0.1.10
10.0.2.20
10.0.2.20

A non-regex solution would be to split the strings by a . and use str.rstrip to remove the leading zeros, then, use str.join to reconstruct the string:

def remove_zeros_from_ip(ip_adr): 
  return '.'.join(p.lstrip('0') or '0' for p in ip_adr.split('.'))

If the only data is an ip, you could use a word boundary \b , match 1+ zeroes and use a capturing group to match 1+ digits and use that group in the replacement.

\b0+(\d+)

Replace with

r'\1'

Regex demo | Python demo

For example

import re

def remove_zeros_from_ip(ip_add):
  string = re.sub(r'\b0+(\d+)', r'\1', ip_add)  
  return string

ip = '10.0.01.10'
print(remove_zeros_from_ip(ip))

ip1 = '10.00.002.20'
print(remove_zeros_from_ip(ip1))

Output

10.0.1.10
10.0.2.20

You can use:

0*(\d+)

In English: greedily find zeros until we encounter any other digit sequence. Store the digit sequence in \1

https://regex101.com/r/sEdwMK/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM