一、运用正则来验证手机号
public static void main(String[] args) {
String phone = "13123456789";
String phoneNumber = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
System.out.println("正则phone中4*:" + phoneNumber);
}
效果为:
二、正则验证身份证号
public static void main(String[] args) {
String idCard = "123456789987654321";
//$1、$2、……表示正则表达式里面第一个、第二个、……括号里面的匹配内容
String idCardNumber = idCard.replaceAll("(\\d{4})\\d{10}(\\w{4})","$1****$2");
System.out.println("身份证号长度:"+idCard.length());
System.out.println("正则idCard中4*:" + idCardNumber);
}
效果为:
3、获取文本中的手机号
public static void main(String[] args) {
String text = "13522158842;托尔斯泰;test2;13000002222;8613111113313";
Pattern pattern = Pattern.compile("(?<!\\d)(?:(?:1[358]\\d{9})|(?:861[358]\\d{9}))(?!\\d)");
Matcher matcher = pattern.matcher(text);
StringBuffer bf = new StringBuffer(64);
while (matcher.find()) {
bf.append(matcher.group()).append(",");
}
int len = bf.length();
if (len > 0) {
bf.deleteCharAt(len - 1);
}
System.out.println(bf.toString());
}