This regex wont work ... help requested!!

I am trying to get rid of empty lines in a .txt file.

This is an example file :

kk
zz

  fd
 
fdf


df

df



  dfd


Now if we can have a cool regex to take care of it.

Help will really be appreciated.

slick
slickdealsAsked:
Who is Participating?
 
StillUnAwareConnect With a Mentor Commented:
BufferedReader br = new BufferedReader(new FileReader("filename"));
String line = null;
while(((line = br.readLine()) != null) && line.length() > 0) {
    System.out.println(line);
}
0
 
StillUnAwareCommented:
The example above uses some other technique while reading data from file. In case You have Your data already read into String, the this regex should help:

String contents = ... // Your file contents
contents = contents.replaceAll("\\n+", "\n"); // this replaces multiple new lines with only one
0
 
hoomanvCommented:
just a correctness to StillUnAware's code

while((line = br.readLine()) != null) {
    if(line.length() > 0)
        System.out.println(line);
}
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
StillUnAwareCommented:
wanted to make it smaller, did a logical mistake. Thanks for pointing it out :)
0
 
hoomanvConnect With a Mentor Commented:
as \r\n is also considered as line terminator in windows
this could be more general
replaceAll("(\\n|\\r\\n)+", "\n");
0
 
CEHJConnect With a Mentor Commented:
>>Now if we can have a cool regex to take care of it.

Not sure how cool this is but ...

if (line.matches("$\\s*))

delete it\ignore it
0
 
danielkullmannConnect With a Mentor Commented:
content = content.replaceAll( "(\r?\n)(\r?\n)+", "\n" );
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.