public class JavaApplication37 { private Pattern pattern; private Matcher matcher; private static final String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; public JavaApplication37() { pattern = Pattern.compile(IPADDRESS_PATTERN); } public static void main(String[] args) { JavaApplication37 java7=new JavaApplication37(); String testIP1="192.168.2.100"; String testIP2="256.100.122.199"; System.out.println("IP1 " +java7.validateIP(testIP1)); System.out.println("IP2 " +java7.validateIP(testIP2)); } public boolean validateIP(final String ip) { matcher = pattern.matcher(ip); return matcher.matches(); } }
輸出結果:
IP1 true
IP2 false
因為testIP2有一個值大於255, 並不合法。
沒有留言:
張貼留言