首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 正則表達式實戰:從文件中提取電話號碼完整解決方案

     編輯:Java 相關知識

需求與核心 API

目標:讀取文本文件,提取其中所有固定電話與手機號碼,存入 Set<String> 去重。核心 API:

  • Pattern.compile(regex):編譯正則
  • Matcher.find():尋找下一個匹配子序列
  • Matcher.group():取得匹配到的字串

電話號碼正則設計

支援格式涵蓋:

  • 手機:86-13xxxxxxxxx、(+86)13xxxxxxxxx、13xxxxxxxxx、8613xxxxxxxxx
  • 固話:02-12345678、02-12345678-123、(+86)02-12345678、含分機號
public static String phoneRegex() {
    // 手機:支援 86、+86、(86)、(+86) 前綴,13/15/18 開頭 11 位
    String mobile = "(?:(\\(\\+?86\\))((13|15|18)[0-9])\\d{8})" +
                    "|(?:86-?((13|15|18)[0-9])\\d{8})" +
                    "|(?:((13|15|18)[0-9])\\d{8})";

    // 固話:支援國碼、區碼、分機
    String landline = "(?:(\\(\\+?86\\))(0[0-9]{2,3}-?)?([2-9][0-9]{6,7})(-[0-9]{1,4})?)" +
                      "|(?:(86-?)?(0[0-9]{2,3}-?)?([2-9][0-9]{6,7})(-[0-9]{1,4})?)";

    return "(?:" + mobile + "|" + landline + ")";
}

從字串提取號碼

public static void extractPhones(String text, Set<String> phoneSet) {
    Pattern pattern = Pattern.compile(phoneRegex());
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        phoneSet.add(matcher.group());
    }
}

文件讀取與整合

public static Set<String> extractFromFile(String filePath) {
    Set<String> phones = new HashSet<>();
    try (BufferedReader br = new BufferedReader(
            new InputStreamReader(new FileInputStream(filePath), "UTF-8"))) {
        String line;
        while ((line = br.readLine()) != null) {
            extractPhones(line, phones);
        }
    } catch (IOException e) {
        System.err.println("讀取失敗: " + e.getMessage());
    }
    return phones;
}

測試驗證

public static void main(String[] args) {
    Set<String> result = extractFromFile("F:/three.txt");
    System.out.println("電話集合:" + result);
}
// 測試文件內容包含多種格式
// 輸出:[86132221, (86)13222144332, 86-13222144332, 32434343, (+86)13222144332, 13888888888]

正則優化建議

  1. 預編譯 Pattern:靜態常量編譯一次,避免重複編譯開銷
  2. 非捕獲群組:用 (?:...) 替代 (...) 減少記憶體佔用
  3. 邊界檢查:實際專案建議加入 \\b 或前後瞄點確保完整匹配
  4. 效能考量:大文件可考慮分塊讀取或使用 Scanner 配合 findInLine

擴展應用

此模式易於擴展至:身分證字號、Email、統一編號、信用卡號等結構化資料提取,只需替換正則模式即可復用整個管線。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved