Java String Whitespace Collapse collapseWhitespace(String text)

Here you can find the source of collapseWhitespace(String text)

Description

Attempts to replace all sequences matching \s+ with a single space.

License

Open Source License

Parameter

Parameter Description
text the text in which to collapse the whitespace

Return

the text with whitespace collapsed from \s+ to a single space

Declaration

public static final String collapseWhitespace(String text) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from w  w w.j  a v a  2 s.  co  m
     * Attempts to replace all sequences matching \s+ with a single space.
     * Intended largely for compression, and programmed conservatively,
     * so it errs on the side of not replacing some \s+ sequences, lest it cause other problems.
     * @param text the text in which to collapse the whitespace
     * @return the text with whitespace collapsed from \s+ to a single space
     */
    public static final String collapseWhitespace(String text) {
        String temp = text.replaceAll("[\\t ]+", " ").replaceAll("^ $", "").replaceAll("\r", "");

        while (temp.indexOf("\n\n") >= 0) {
            temp = temp.replaceAll("\n\n", "\n");
        }
        return temp;
    }
}

Related

  1. collapseWhitespace(String s)
  2. collapseWhitespace(String s, boolean trim)
  3. collapseWhitespace(String str)
  4. collapseWhitespace(String string)
  5. collapseWhiteSpace(String string)
  6. collapseWhiteSpace(String text)
  7. collapseWhiteSpace(StringBuffer oriText)
  8. collapseWhiteSpaces(String str)