Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zeros from IP Address with C#

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

like image 733
mad madane Avatar asked Mar 31 '12 05:03

mad madane


People also ask

How do you remove leading zeros INT?

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.

Can IP addresses have leading zeros?

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.

How do you remove leading zeros from an IP address in Python?

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 '.


2 Answers

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

like image 190
Brent Avatar answered Nov 15 '22 22:11

Brent


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.

like image 26
Cody Gray Avatar answered Nov 15 '22 23:11

Cody Gray