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

Java 正則提取數字並去重:從基礎寫法到封裝 Bean 實戰

     編輯:Java 相關知識

場景:從字符串中提取特定模式的數字

需求:給定字符串 "QQ120282458,QQ120282458 QQ125826",提取長度 5-12 位的純數字,並去除重複值。

方案一:基礎版 — ArrayList + HashSet 去重

public class MatchTest {
    public static void main(String[] args) {
        String regex = "[0-9]{5,12}";
        String input = "QQ120282458,QQ120282458 QQ125826";

        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        List<String> list = new ArrayList<>();

        while (m.find()) {
            list.add(m.group(0));
        }

        System.out.println("去除重複值前:" + list); // [120282458, 120282458, 125826]

        // HashSet 去重
        Set<String> set = new HashSet<>(list);
        list.clear();
        list.addAll(set);

        System.out.println("去除重複值後:" + list); // [125826, 120282458] (順序不保證)
    }
}

方案二:進階版 — 封裝為可復用 Bean

將正則邏輯封裝進 MatchTest 類,構造器自動完成匹配與去重,對外暴露只讀屬性:

public class MatchTest {
    private final String regex;
    private final String input;
    private final List<String> result;

    public MatchTest(String regex, String input) {
        this.regex = regex;
        this.input = input;
        List<String> temp = new ArrayList<>();
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        while (m.find()) {
            temp.add(m.group());
        }
        // LinkedHashSet 保持插入順序同時去重
        this.result = new ArrayList<>(new LinkedHashSet<>(temp));
    }

    public String getRegex() { return regex; }
    public String getInput() { return input; }
    public List<String> getResult() { return Collections.unmodifiableList(result); }

    public static void main(String[] args) {
        MatchTest mt = new MatchTest("[0-9]{5,12}", "QQ120282458,QQ120282458 QQ125826");
        mt.getResult().forEach(System.out::println);
    }
}

關鍵優化點

  • 順序保持:使用 LinkedHashSet 替代 HashSet,保證去重後順序與首次出現順序一致。
  • 泛型化:集合聲明使用 List<String> 而非原始類型,避免無檢查警告。
  • 不可變視圖:getResult() 返回 Collections.unmodifiableList,防止外部誤修改內部狀態。
  • 預編譯 Pattern:高頻調用場景下,建議將 Pattern 定義為 static final 常量,避免重複編譯正則。

常用正則工具推薦

總結

正則提取配合 LinkedHashSet 去重是處理「提取並去重」場景的標準套路。封裝為 Bean 後可方便地在 Service 層復用,並通過構造器參數化正則與輸入,靈活應對不同業務需求。

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