[英]Python - remove leading zeros from IP addresses
I am trying to remove leading zeros from IP addresses but it's not working我正在尝试从 IP 地址中删除前导零,但它不起作用
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 八位字节,然后将字符串中的八位字节转换为 int,然后再转换回 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 .
或
^
(行首),后跟除 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: 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:并使用
str.rstrip
删除前导零,然后使用str.join
重建字符串:
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.如果唯一的数据是 ip,您可以使用单词边界
\b
,匹配 1+ 个零并使用捕获组来匹配 1+ 个数字并在替换中使用该组。
\b0+(\d+)
Replace with用。。。来代替
r'\1'
Regex demo |正则表达式演示| Python demo
Python 演示
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 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
将数字序列存储在
\1
https://regex101.com/r/sEdwMK/1 https://regex101.com/r/sEdwMK/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.