需求:給定字符串 "QQ120282458,QQ120282458 QQ125826",提取長度 5-12 位的純數字,並去除重複值。
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] (順序不保證)
}
}
將正則邏輯封裝進 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 定義為 static final 常量,避免重複編譯正則。正則提取配合 LinkedHashSet 去重是處理「提取並去重」場景的標準套路。封裝為 Bean 後可方便地在 Service 層復用,並通過構造器參數化正則與輸入,靈活應對不同業務需求。