正則表達式判斷IP地址是否合法(Java)

package others;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 判斷IP地址是否合法
 * @author YangXian
 *
 */

/*
 * 所有的一位數(1):				\d
 * 所有的二位數(2):				[1-9]\d
 * 1開頭的三位數(所有)(3):		1\d{2}
 * 2開頭的三位數(200-255)(4):	2[0-4]\d|25[0-5]
 * 
 * 每個數可能爲(format):		^((1)|(2)|(3)|(4))
 * 總規則爲:					^(format)(\.(format)){3}$
 * 
 * 最終規則:					^(\d|[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}$
 * 
 */

public class IPCheck {
	public  static boolean ipCheck(String str) {
		if( str != null && !str.isEmpty()){
			String pattern = "^(\\d|[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}$";
			//String regex="^([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}$";
			if(str.matches(pattern))
				return true;
			return false;
			
		}
		return false;
	}

	public static void main(String[] args) {
		System.out.println(ipCheck("192.168.0.1"));
        System.out.println(ipCheck("256.168.0.1"));

	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章