正則表示式校驗身份證號
阿新 • • 發佈:2019-01-29
最近在看正則表示式的一些東西,突然想起之前寫的一個關於身份證號碼校驗的小程式。當時寫身份證的校驗的時候,沒有考慮到輸入格式的校驗。程式的健壯性很差,現在我就用正則表示式來做身份證格式校驗,體驗一下正則表示式的奇妙用法。
正則表示式是對字串操作的一種邏輯公式,就是用事先定義好的一些特定字元、及這些特定字元的組合,組成一個“規則字串”,這個“規則字串”用來表達對字串的一種過濾邏輯。常見的用法包括模糊搜尋和搜尋過濾。
字符集:
[abc] a、b 或 c(簡單類) [^abc] 任何字元,除了 a、b 或 c(否定) [a-zA-Z] a 到 z 或 A 到 Z,兩頭的字母包括在內(範圍) [a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](並集) [a-z&&[def]] d、e 或 f(交集) [a-z&&[^bc]] a 到 z,除了 b 和 c:[ad-z](減)
預定義字符集:
. 任何字元(與行結束符可能匹配也可能不匹配)
\d 數字:[0-9]
\s 空白字元:[ \t\n\x0B\f\r]
\w 單詞字元:[a-zA-Z_0-9]
數量詞:
{m}:m個字元
{m,n}:m到n個字元
{?}:{0,1}
{+}:{1,n}
{*}:{0,n}
^:開始
$:結束
關鍵程式碼:
import java.util.Arrays;
import java.util.Scanner;
public class CheckIDCardDome {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
while (true) {
System.out.print("Please input you IdCard number:");
String num = console.nextLine();
char[] id = {};
for (int i = 0; i < num.length(); i++) {
id = Arrays.copyOf(id, id.length + 1 );
id[id.length - 1] = num.charAt(i);
}
boolean IsFormRight = verForm(num);
if (IsFormRight) {
boolean IsCorrect = verify(id);
if (IsCorrect) {
System.out.println("Id is right!");
return;
}
else {
System.out.println("Id is wrong!");
}
}
}
}
<------------------身份證格式的正則校驗----------------->
public static boolean verForm(String num) {
String reg = "^\\d{15}$|^\\d{17}[0-9Xx]$";
if (!num.matches(reg)) {
System.out.println("Format Error!");
return false;
}
return true;
}
<------------------身份證最後一位的校驗演算法----------------->
public static boolean verify(char[] id) {
int sum = 0;
int w[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
char[] ch = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
for (int i = 0; i < id.length - 1; i++) {
sum += (id[i] - '0') * w[i];
}
int c = sum % 11;
char code = ch[c];
char last = id[id.length-1];
last = last == 'x' ? 'X' : last;
return last == code;
}
}
OK,關於用正則表示式做身份證校驗的過程就是這樣。
注:正則匹配的相關介紹來自Java API文件中Pattern類的說明部分,身份證最後一位的校驗演算法,可自行百度。