该方法用于提取复杂的短信中的验证码,还可以用于其他方面的提取或者替换。如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");