1.手機號隱藏處理
String content = "我是中國人手機號,中國碼農"; Pattern pattern = Pattern.compile("(?<!\\d)(?:(?:1[34578]\\d{9})|(?:861[34578]\\d{9}))(?!\\d)"); Matcher matcher = pattern.matcher(content); StringBuffer bf = new StringBuffer(128); while (matcher.find()) { content = content.replace(matcher.group(), matcher.group().substring(0,3)+"********"); } System.out.println(content);
2.身份證隱藏處理
String content = "我是中國人身份證號,中國碼農"; String regex ="([1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx])|([1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3})"; Pattern p = Pattern.compile(regex); Matcher matcher = p.matcher(content); while (matcher.find()){ content = content.replace(matcher.group(), matcher.group().substring(0,6)+"********"); } System.out.println(content);
3.中文匹配:* 零次或多次匹配前面的字符或子表達式
String content = "我是中國人,中國碼農,身份證你是誰號碼你好"; Pattern pattern = Pattern.compile(".*身份證.*號碼.*"); Matcher matcher = pattern.matcher(content); while (matcher.find()) { String group = matcher.group(); System.out.println(group); //匹配上了 } System.out.println(content); }