個人學習總結,供大家參考,不足之處見諒。
提前補充一個用到的知識點
1、Character.getNumericValue(char ch)通常情況下,字符本身可以直接轉化爲數字值就直接轉化。
2、如果該字符不有一個數字值,則返回-1。如果字符具有一個數字值,該值不能被表示爲一個非負整數(例如,一個分數值),則返回-2,再將其轉換成對應的ASCII碼。
package test;
public class RegExUtils {
public static boolean idCard(String no){
// 對身份證號進行長度等簡單判斷
if (no == null || no.length() != 18 || !no.matches("\\d{17}[0-9X]"))
{
return false;
}
// 1-17位相乘因子數組
int[] factor = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
// 18位隨機碼數組
char[] random = "10X98765432".toCharArray();
// 計算1-17位與相應因子乘積之和
int total = 0;
for (int i = 0; i < 17; i++)
{
total += Character.getNumericValue(no.charAt(i)) * factor[i];
}
// 判斷隨機碼是否相等
return random[total % 11] == no.charAt(17);
}
public static boolean checkEmail(String email)
{// 驗證郵箱的正則表達式
String format = "\\p{Alpha}\\w{1,}[@][a-z0-9]{3,}[.]\\p{Lower}{2,}";
//p{Alpha}:內容是必選的,和字母字符[\p{Lower}\p{Upper}]等價。如:[email protected]不是合法的。
//w{2,15}: 2~15個[a-zA-Z_0-9]字符;w{}內容是必選的。 如:[email protected]是合法的。
//[a-z0-9]{3,}:至少三個[a-z0-9]字符,[]內的是必選的;如:[email protected]是不合法的。
//[.]:'.'號時必選的; 如:dyh200896@163com是不合法的。
//p{Lower}{2,}小寫字母,兩個以上。如:[email protected]是不合法的。
if (email.matches(format))
{
return true;// 郵箱名合法,返回true
}
else
{
return false;// 郵箱名不合法,返回false
}
}
public static void main(String[] args) throws Exception
{
// 正確
System.out.println(idCard("412824199501247719"));
// 錯誤
System.out.println(idCard("432831196411150812"));
String email = "[email protected]"; // 需要進行驗證的郵箱
if (checkEmail(email))// 驗證郵箱
{
System.out.println(email+"\n是合法的郵箱名。");
}else
{
System.out.println(email+"\n不是合法的郵箱名。");
}
}
}