引言
java中我們會常用一些判斷如IP、電子郵箱、電話號碼的是不是合法,那么我們怎么來判斷呢,答案就是利用正則表達式來判斷了,廢話不多說,下面就是上代碼。
1:判斷是否是正確的IP
1 /** 2 * 用正則表達式進行判斷 3 */ 4 public boolean isIPAddressByRegex(String str) { 5 String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"; 6 // 判斷ip地址是否與正則表達式匹配 7 if (str.matches(regex)) { 8 String[] arr = str.split("\\."); 9 for (int i = 0; i < 4; i++) { 10 int temp = Integer.parseInt(arr[i]); 11 //如果某個數字不是0到255之間的數 就返回false 12 if (temp < 0 || temp > 255) return false; 13 } 14 return true; 15 } else return false; 16 }
2:判斷是否是正確的郵箱地址
1 /** 2 *正則表達式驗證郵箱 3 */ 4 public static boolean isEmail(String email) { 5 if (email == null || "".equals(email)) return false; 6 String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; 7 return email.matches(regex); 8 }
3:判斷是否是手機號碼
1 /** 2 *正則表達式驗證手機 3 */ 4 public static boolean orPhoneNumber(String phoneNumber) { 5 if (phoneNumber == null || "".equals(phoneNumber)) 6 return false; 7 String regex = "^1[3|4|5|8][0-9]\\d{8}$"; 8 return phoneNumber.matches(regex); 9 }