tags:

views:

74

answers:

2

I want to split the /n from my string in Java. For example, I have one String field which has 2 lines space ( /n). I have to find out lines ( wherever mopre than one lines is coming) and should replace with one line spaces.

"This is Test Message  


  thanks
  Zubair
"

From the above example, there are more spaces between "This is Test Message" and "thanks". So i want to reduce as only one line instead of 2 lines.How to do that?

+3  A: 
str.replaceAll("(\\r\\n?|\\n){3,}", "$1$1");

What this does is replace three or more line terminators (\r, \n or \r\n) with two line terminators so any double blank lines are replaced with a single blank line, if I understand what you want correctly.

cletus
Thanks for your reponse i will try and let u know
Gnaniyar Zubair
I like the use of the references and explicit quantifier. However this won't work correctly if intermediate lines are blank-but-not-empty.
pst
@pst True, but no clear definition of "empty" was given. Allowing for lines with white space on them is easily added by putting `\s*` in there.
cletus
+1  A: 

I don't know how to use regex, but you can use a StringTokenizer:

String reduceToOneLine(String input){
    // Note that this means both \r and \n are tokens, not that they have to appear together.
    StringTokenizer tokenizer = new StringTokenizer(input, "\r\n"); 
    StringBuffer output = new StringBuffer();
    while(tokenizer.hasMoreTokens()){
        output.append(tokenizer.nextToken());
    }
    return output.toString();
}

This splits the string on line breaks, then adds each line to a new string (the tokenizer treats multiples of its delimiter as one, so you'll be left with just one line break between lines).

Brendan Long
Thanks for your reponse i will try and let u know
Gnaniyar Zubair
As I understand it, the OP wants to reduce two or more consecutive blank lines to one. This just gets rid of *all* line breaks.
Alan Moore