報表匯出時,檔案名稱常含 Windows 檔案系統非法字符(\ ? * : [ ] /),需預先清理。本文提供可直接生產的 Java 程式碼片段。
// 匹配 Windows 非法檔名字符:\ ? * : [ ] /
Pattern pattern = Pattern.compile("[\\\\\\?*:\\[\\]/]");
// 建立 Matcher
Matcher systemMatcher = pattern.matcher(systemName);
Matcher unitMatcher = pattern.matcher(unitCodeName);
// 替換為空字串(移除)
String cleanSystemName = systemMatcher.replaceAll("");
String cleanUnitName = unitMatcher.replaceAll("");
| 字符 | 正則寫法 | 說明 |
|---|---|---|
\ | \\\\ | Java 字串雙重轉義:\\ → 正則 \\ → 匹配單一反斜線 |
? * : | \\?*: | 字面量匹配,? * 需轉義 |
[ ] | \\\\[\\\\] | 字元類別邊界需轉義 |
/ | / | 正則無特殊含義,直接寫 |