/** 移除所有空白字符:空格、\t \r \n \f 等 */
public static String removeAllWhitespace(String input) {
return input == null ? null : input.replaceAll("\\s+", "");
}
\\s = [ \t\n\r\f],+ 連續合併,替換為空串。
| 需求 | 正則 | 代碼 |
|---|---|---|
| 僅移除首尾空白 | ^\\s+|\\s+$ | input.trim() (JDK 11+ strip() 更安全) |
| 移除所有空格 (保留換行) | | input.replace(" ", "") |
| 移除換行符 (\n \r) | [\\r\\n]+ | input.replaceAll("[\\r\\n]+", "") |
| 移除製表符 (\t) | \\t | input.replace("\t", "") |
| 合併連續空白為單空格 | \\s+ | input.replaceAll("\\s+", " ") |
| 移除所有不可见字符 (含零寬空格等) | \\p{C} | input.replaceAll("\\p{C}", "") |
public final class StringCleaner {
private StringCleaner() {}
/** 移除所有空白字符 (最常用) */
public static String removeWhitespace(String s) {
return s == null ? null : s.replaceAll("\\s+", "");
}
/** 移除首尾空白,中間合併為單空格 */
public static String normalize(String s) {
if (s == null) return null;
return s.trim().replaceAll("\\s+", " ");
}
/** 移除換行/回車,保留空格/製表 */
public static String removeLineBreaks(String s) {
return s == null ? null : s.replaceAll("[\\r\\n]+", "");
}
/** 移除所有控制字符 (含零寬空格、BOM 等) */
public static String removeControlChars(String s) {
return s == null ? null : s.replaceAll("\\p{C}", "");
}
/** HTML 內容清洗:去標籤、解實體、正規化空白 */
public static String cleanHtml(String html) {
if (html == null) return null;
String text = html.replaceAll("<[^>]*>", "") // 去標籤
.replaceAll("&[a-z]+;", "") // 簡易去實體
.replaceAll("\\s+", " ")
.trim();
return text;
}
}
Pattern:private static final Pattern WS = Pattern.compile("\\s+");String.replace (非正則) 更快Matcher.appendReplacement 避免全量內存
@Test
public void test() {
String dirty = " Hello\tWorld\n\r\nGood\tMorning ";
assertEquals("HelloWorldGoodMorning", StringCleaner.removeWhitespace(dirty));
assertEquals("Hello World Good Morning", StringCleaner.normalize(dirty));
assertEquals(" Hello\tWorldGood\tMorning ", StringCleaner.removeLineBreaks(dirty));
}