《java-正则表达式提取复杂短信验证码》-(用户:654321,的验证码是:【123456】)

来源:互联网 发布:js传值给jsp页面 编辑:程序博客网 时间:2024/06/05 19:28

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