用正则表达式验证IPv6地址的例子

前端之家收集整理的这篇文章主要介绍了用正则表达式验证IPv6地址的例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


public class Hello {
  public boolean isIPv6(String address)
     {
         boolean result = false;
         String regHex = "(\\p{XDigit}{1,4})";
         
         //没有双冒号
         String regIPv6Full = "^(" + regHex + ":){7}" + regHex + "$";
         
         //双冒号在中间或者没有双冒号
         String regIPv6AbWithColon = "^(" + regHex + "(:|::)){0,6}" + regHex
                 + "$";
         
         //双冒号开头
         String regIPv6AbStartWithDoubleColon = "^(" + "::(" + regHex
                 + ":){0,5}" + regHex + ")$";
         
         String regIPv6 = "^(" + regIPv6Full + ")|("
                 + regIPv6AbStartWithDoubleColon + ")|(" + regIPv6AbWithColon
                 + ")$";

         //System.out.println("regIPv6 =" + regIPv6);
         //regIPv6 =^(^((\p{XDigit}{1,4}):){7}(\p{XDigit}{1,4})$)|(^(::((\p{XDigit}
         //{1,4}):){0,5}(\p{XDigit}{1,4}))$)|(^((\p{XDigit}{1,4})(:|::)){0,6}(\p
         //{XDigit}{1,4})$)$

         //等价于^(^::$)|(^([\\d|a-fA-F]{1,4}:){7}([\\d|a-fA-F]{1,4})$)|(^(::
         //(([\\d|a-fA-F]{1,5}([\\d|a-fA-F]{1,4}))$)|(^(([\\d|a-fA-F]{1,4})
         //(:|::)){0,6}([\\d|a-fA-F]{1,4})$)$
         
         //下面还要处理地址为::的情形和地址包含多于一个的::的情况(非法)
         if (address.indexOf(":") != -1)
         {
             if (address.length() <= 39)
             {
                 String addressTemp = address;
                 int doubleColon = 0;
                 if(address.equals("::"))return true;
                 while (addressTemp.indexOf("::") != -1)
                 {
                     addressTemp = addressTemp.substring(addressTemp
                             .indexOf("::") + 2,addressTemp.length());
                     doubleColon++;
                 }
                 if (doubleColon <= 1)
                 {
                     result = address.matches(regIPv6);
                 }
             }
         }
        return result;
     }
public static void main(String[] args)
{
  Hello hello=new Hello();
  boolean bln=false;
  bln=hello.isIPv6("::");
  System.out.println("Start...") ;
  if (bln)
   System.out.println("OK") ;
  else
   System.out.println("NO") ;
}
}
原文链接:https://www.f2er.com/regex/363128.html

猜你在找的正则表达式相关文章