Java用正则表达式判断是否为IP

来源:互联网 发布:linux telnet命令 端口 编辑:程序博客网 时间:2024/05/22 06:05

Java用正则表达式判断是否为IP

1、Java源码

Java代码  收藏代码
  1. /** 
  2.  * @Title:IpAddress.java 
  3.  * @Package:com.you.dao 
  4.  * @Description:用正则表达式判断是否为IP 
  5.  * @Author: 游海东 
  6.  * @date: 2014年3月4日 下午10:55:06 
  7.  * @Version V1.2.3 
  8.  */  
  9. package com.you.dao;  
  10.   
  11. import java.util.regex.Matcher;  
  12. import java.util.regex.Pattern;  
  13.   
  14. /** 
  15.  * @类名:IpAddress 
  16.  * @描述:用正则表达式判断是否为IP 
  17.  * @Author:Administrator 
  18.  * @date: 2014年3月4日 下午10:55:06 
  19.  */  
  20. public class IpAddress   
  21. {  
  22.     public static class IpAdd  
  23.     {  
  24.         public boolean isIP(String addr)  
  25.         {  
  26.             if(addr.length() < 7 || addr.length() > 15 || "".equals(addr))  
  27.             {  
  28.                 return false;  
  29.             }  
  30.             /** 
  31.              * 判断IP格式和范围 
  32.              */  
  33.             String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";  
  34.               
  35.             Pattern pat = Pattern.compile(rexp);    
  36.               
  37.             Matcher mat = pat.matcher(addr);    
  38.               
  39.             boolean ipAddress = mat.find();  
  40.   
  41.             return ipAddress;  
  42.         }  
  43.     }  
  44.   
  45.     /** 
  46.      * @Title : main 
  47.      * @Type : IpAddress 
  48.      * @date : 2014年3月4日 下午10:55:06 
  49.      * @Description : IP可能的范围是0-255.0-255.0-255.0-255 
  50.      * @param args 
  51.      */  
  52.     public static void main(String[] args)   
  53.     {  
  54.         /** 
  55.          * 符合IP地址的范围 
  56.          */  
  57.          String oneAddress = "10.127.30.45";  
  58.          /** 
  59.          * 符合IP地址的长度范围但是不符合格式 
  60.          */  
  61.          String twoAddress = "127.30.45";  
  62.          /** 
  63.          * 不符合IP地址的长度范围 
  64.          */  
  65.          String threeAddress = "7.0.4";  
  66.          /** 
  67.          * 不符合IP地址的长度范围但是不符合IP取值范围 
  68.          */  
  69.          String fourAddress = "255.255.255.2567";  
  70.            
  71.          IpAdd ipAdd = new IpAdd();  
  72.            
  73.          //判断oneAddress是否是IP  
  74.          System.out.println(ipAdd.isIP(oneAddress));  
  75.            
  76.          //判断twoAddress是否是IP  
  77.          System.out.println(ipAdd.isIP(twoAddress));  
  78.            
  79.          //判断threeAddress是否是IP  
  80.          System.out.println(ipAdd.isIP(threeAddress));  
  81.            
  82.          //判断fourAddress是否是IP  
  83.          System.out.println(ipAdd.isIP(fourAddress));  
  84.     }  
  85.   
  86. }  

 2、运行结果

 

 

 

true
false
false
false


转自:http://you23hai45.iteye.com/blog/2026855?utm_source=tuicool

原创粉丝点击