The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.regex  [26 examples] > Lines  [6 examples]

e446. Removing Line Termination Characters from a String

A line termination character sequence is a character or character pair from the set: \n, \r, \r\n, \u0085, \u2028, and \u2029.

Note: The character pair \n\r is considered a two-line terminator character and therefore will be replaced with two spaces.

    // Returns a version of the input where all line terminators
    // are replaced with a space.
    public static CharSequence removeLineTerminators(CharSequence inputStr) {
        String patternStr = "(?m)$^|[\\r\\n]+\\z";
        String replaceStr = " ";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(inputStr);
        return matcher.replaceAll(replaceStr);
    }

 Related Examples
e441. Using a Regular Expression to Filter Lines from a Reader
e442. Implementing a FilterReader to Filter Lines Based on a Regular Expression
e443. Matching Line Boundaries in a Regular Expression
e444. Matching Across Line Boundaries in a Regular Expression
e445. Reading Lines from a String Using a Regular Expression

See also: Flags    Groups    Paragraphs    Searching and Replacing    Tokenizing   


© 2002 Addison-Wesley.