Remove leading zeros from IP address with C #

I have the IP address "", how can I remove the leading zeros to get this ""? At the moment I am using a regex like this

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


Is there any other way to achieve this result without using a regular expression?

I am using Visual C # 3.0 for this code


source to share

3 answers

Yes, there's a much better way out there than using regular expressions to do this.

Try the System.Net.IpAddress

instead .

There is a method ToString()

that returns the standard notation of the public version of the IP address. This is probably what you want here.



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



As @Brent pointed out, IPAddress.TryParse

treats leading zeros as octal and will result in bad answers. One way to fix this problem is to use a RegEx.Replace

replacement. I personally like this one, which looks for 0 followed by any number of numbers.

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


He will return

. This will only work if all text is an IP address.



All Articles