該方法用於提取複雜的短信中的驗證碼,還可以用於其他方面的提取或者替換。如156****4662,手機號隱藏。也可以用這種方式。
可以利用組的概念,即對要提取的部分用“()”括起來。
public static void main(String[] args) {
String str = "用戶:654321,的驗證碼是:【123456】";
if (str != null) {
Pattern p = Pattern.compile("【(\\d+)】");
Matcher m = p.matcher(str);
while(m.find()) {
System.out.println("匹配結果:"+m.group());
System.out.println("提取組1:"+m.group(1));
}
}
}
運行結果:
匹配結果:【123456】
提取組1:123456
String tel = "15666664662";
tel = tel.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");