缩写规则:如果完整部分为零,那么它可以写为0,如果两个或多个连续部分为零,则可以忽略它们,例如,如果我们有 1234 0000 0000 0000 1212 它可以写成 1234 :: 1212
答案 0 :(得分:2)
显然这就是你要找的东西:
using System.Text.RegularExpressions;
static void Main(string[] args)
{
Console.WriteLine(Compress("1234:0000:0000:0000:1212"));
Console.ReadLine();
}
private static string Compress(string ip)
{
var removedExtraZeros = ip.Replace("0000","*");
//2001:0008:*:CD30:*:*:*:0101
var blocks = ip.Split(':');
var regex = new Regex(":0+");
removedExtraZeros = regex.Replace(removedExtraZeros, ":");
//2001:8:*:CD30:*:*:*:101
var regex2 = new Regex(":\\*:\\*(:\\*)+:");
removedExtraZeros = regex2.Replace(removedExtraZeros, "::");
//2001:8:*:CD30::101
return removedExtraZeros.Replace("*", "0");
}
*来源:IPv6 Abbreviation(zero blocks compression) logic. I'm using c#