Remove leading zeros from IP address with C #
I have the IP address "127.000.000.001", how can I remove the leading zeros to get this "127.0.0.1"? At the moment I am using a regex like this
Regex.Replace("127.000.000.001", "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
Yes, there's a much better way out there than using regular expressions to do this.
Try the System.Net.IpAddress
class 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.
source to share
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 192.168.090.009.
http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/21510004-b719-410e-bbc5-a022c40a8369
source to share
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("010.001.100.001", "0*([0-9]+)", "${1}")
He will return 10.1.100.1
. This will only work if all text is an IP address.
source to share