public class UtilRegex {
public static void main(String[] args) {
//省份证15位或者18位
String regex = "^[1-9](\\d{16}|\\d{13})([0-9]|x)$";
Scanner sc = new Scanner (System.in);
System.out.println ("请输入身份证号码");
String idCardNumber = sc.next ( );
int c = idCardNumber.length ( );
/*String idCardNumber = "222222222222222222";*/
boolean isValid = idCardNumber.matches (regex);
if (isValid) {
System.out.println ("身份证号码有效");
//身份證號碼中間使用*代替.處理敏感數據
char[] newChange = idCardNumber.toCharArray ( );
if (c == 18) {
for (int i = 0; i < newChange.length; i++) {
if (i > 2 & i < 14) {
newChange[i] = '*';
}
}
} else {
for (int i = 0; i < newChange.length; i++) {
if (i > 2 & i < 11) {
newChange[i] = '*';
}
}
}
System.out.println (newChange );
//char數組轉換爲字符串
String sum = new String (newChange);
System.out.println (sum);
} else {
System.out.println ("身份证号码无效");
}
}
matches函数为了检测前面变量是否符合后面正则条件