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

Java 字符串清洗:正則移除空格、換行、製表符等不可见字符

     編輯:Java 程式設計入門

一行代碼方案 (推薦)


/** 移除所有空白字符:空格、\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)\\tinput.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));
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved