Remove leading zeros from IP Address with C#

2019-07-02 00:38发布

问题:

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.