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
Use the inbuilt replaceAll() method of the String class which accepts two parameters, a Regular Expression, and a Replacement String. To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter. This method replaces the matched value with the given string.
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. For example, "0.1.
and use str. rstrip to remove the leading zeros, then, use str. join to reconstruct the string: def remove_zeros_from_ip(ip_adr): return '.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With