《java-正則表達式提取複雜短信驗證碼》-(用戶:654321,的驗證碼是:【123456】)

該方法用於提取複雜的短信中的驗證碼,還可以用於其他方面的提取或者替換。如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");
發佈了170 篇原創文章 · 獲贊 56 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章