Remove leading zeros from IP Address with C#

烂漫一生 提交于 2019-12-10 16:26:10

问题


I have an IP like this "127.000.000.001" how can I remove the leading zeros to get this "127.0.0.1"? For now i use regex like this

Regex.Replace("127.000.000.001", "0*([0-9]+)", "${1}")

Is there any other way to achieve this result without using regex?

I use visual C# 3.0 for this code


回答1:


Yes, there's a much better way than using regular expressions for this.

Instead, try the System.Net.IpAddress class.

There is a ToString() method that will return a human-readable version of the IP address in its standard notation. This is probably what you want here.




回答2:


The IP Address object will treat a leading zero as octal, so it should not be used to remove the leading zeros as it will not handle 192.168.090.009.

http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/21510004-b719-410e-bbc5-a022c40a8369




回答3:


As stated by @Brent, IPAddress.TryParse treats leading zeros as octal and will result in a bad answer. One way of fixing this issue is to use a RegEx.Replace to do the replacement. I personally like this one that looks for a 0 followed by any amount of numbers.

Regex.Replace("010.001.100.001", "0*([0-9]+)", "${1}")

It will return 10.1.100.1. This will work only if the entire text is an IP Address.



来源:https://stackoverflow.com/questions/9953353/remove-leading-zeros-from-ip-address-with-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!