如何用一个空行替换多个空格和换行符

时间:2014-01-16 15:23:08

标签: java string string-formatting

如何删除字符串中的多个空格和换行符,但为每组空行保留至少一个空行。

例如,更改:

"This      is



a        string.




Something."

"This is

a string.

Something."

我使用.trim()从字符串的开头和结尾删除空格,但我找不到任何可以删除字符串中多个空格和换行符的内容。

我想保留一个空格和一个换行符。

3 个答案:

答案 0 :(得分:7)

删除多个空格/换行符的单行解决方案,但保留多个空白行中至少一个空行:

str = str.replaceAll("(?m)(^ *| +(?= |$))", "").replaceAll("(?m)^$([\r\n]+?)(^$[\r\n]+?^)+", "$1");

每条线都被修剪。


这是一些测试代码:

String str = "   This       is\r\n    " + 
        "\r\n" + 
        "   \r\n   " + 
        " \r    \n   \n  " +
        "\r\n" + 
        "                a        string.   ";
str = str.trim().replaceAll("(?m)(^ *| +(?= |$))", "").replaceAll("(?m)^$([\r\n]+?)(^$[\r\n]+?^)+", "$1");
System.out.println(str);

输出:

This is

a string.

答案 1 :(得分:1)

这是我在经过一些测试后得出的......

public String keepOneWS(String str) {
    Pattern p = Pattern.compile("(\\s+)");
    Matcher m = p.matcher(str);

    Pattern pBlank = Pattern.compile("[ \t]+");
    String newLineReplacement = System.getProperty("line.separator") + 
            System.getProperty("line.separator");

    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        if(pBlank.matcher(m.group(1)).matches()) {
            m.appendReplacement(sb, " ");   
        } else {
            m.appendReplacement(sb, newLineReplacement);
        }
    }
    m.appendTail(sb);

    return sb.toString().trim();
}

public void testKeepOneWS()  {
    String str = "   This   \t    is\r\n    " + 
            "\r\n" + 
            "   \r\n   " + 
            " \r    \n  \t  \n  " +
            "\r\n" + 
            "                a   \t     string.   \t ";
    String expected = "This is" + System.getProperty("line.separator")+ 
            System.getProperty("line.separator") + "a string.";
    String actual = keepOneWS(str);
    System.out.println("'" + actual + "'");
    assertEquals(expected, actual);
}

在捕获一个空白集合之后,检查它是否仅由空格组成,如果是,则将该集合替换为单个空格,否则该集合由空格和行终止符组成,在这种情况下,该组被替换一线终结者。

输出结果为:

'This is

a string.' 

答案 2 :(得分:0)

之前的建议将修剪所有空格,包括换行符,并用一个空格替换它们。

 text.replaceAll("\\n\\s*\\n", "\\n").replaceAll("[ \\t\\x0B\\f]+", " ").trim());

首先,它用一个换行符替换任何只有空格的换行实例,然后将任何其他空格缩小到单个空格,忽略换行符。

相关问题