写一方法用于判断一个字符串是否是IP形式( 要求用异常处理完成 )

解决方案 »

  1.   


     public static void main(String [] args){
     String[] str={"123.255.255.123","123.255.255.123","198.126.255.255","255.255.255.0"
     };
     Pattern pattern =Pattern.compile(".*?((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d).*?");
     boolean flag=false;
     Matcher matcher=null;
     for(int i=0;i<str.length;i++)
     {
     matcher = pattern.matcher(str[i]);
     flag=matcher.matches();
     if(!flag)
     {
     break;
     }  
     }
     if(!flag)
     {
     System.out.println("check fail");
     }
     else
     {
     System.out.println("check success");
     }
        }
      

  2.   

    当flag为false的时候抛出异常就行了。
      

  3.   

    不明白为什么非要用异常机制,不过编写了一个不带异常的经调试成功!楼主可以参考一下!
    package csdn;import java.util.regex.*;public class IsIP { /**
     * @param args判断是否是IP
     *            202.1.33.343
     */
    public static boolean isIp(String str) {
    String strP = "[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}";
    Pattern ptn = Pattern.compile(strP);
    Matcher matcher = ptn.matcher(str);
    if (matcher.matches()) {
    return true;
    } else {
    return false;
    }
    } public static void main(String[] args) {
    // TODO Auto-generated method stub
    String[] str = { "+62334343.2388", "234.34.0.22", "abc.23.0.2",
    "8888.202.33.22" };
    for (int i = 0; i < str.length; i++) {
    if (isIp(str[i])) {
    System.out.println(i + "是IP地址");
    } else {
    System.err.println(i + "不是IP地址");
    }
    }
    }}运行结果为:
    1是IP地址
    0不是IP地址
    2不是IP地址
    3不是IP地址
      

  4.   

    String strP = "[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}";
    我晕,正则光判断是不是1-3位数字了,忘了判断是不是超过255.特此道歉!
      

  5.   

    利用正则表达式分解和转换IP地址 
      function IP2V(ip) //IP地址转换成对应数值 
      { 
      re=/(d+).(d+).(d+).(d+)/g //匹配IP地址的正则表达式 
      if(re.test(ip)) 
      { 
      return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1 
      } 
      else 
      { 
      throw new Error("Not a valid IP address!") 
      } 
      }