Bernd
Bernd

Reputation: 31

Java: Count empty lines in a text file/string

I am using the following code to count empty lines in Java, but this code returns a greater number of empty lines than there are.

int countEmptyLines(String s) {
int result=0;
Pattern regex = Pattern.compile("(?m)^\\s*$");
Matcher testMatcher = regex.matcher(s);
while (testMatcher.find())
{
  result++;
}
return result;}

What am I doing wrong or is there a better way to do it?

Upvotes: 2

Views: 7829

Answers (3)

Bernd
Bernd

Reputation: 31

I found a way to fix my own regex while I was at lunch:

Pattern regex = Pattern.compile("(?m)^\\s*?$");

The '?' makes the \s* reluctant, meaning it will somehow not match the character that '$' will match.

Upvotes: 1

0xCAFEBABE
0xCAFEBABE

Reputation: 5666

\s matches any whitespace, which is either a space, a tab or a carriage return/linefeed.

The easiest way to do this is to count chains of successive EOL characters. I write EOL, because you need to determine which character denotes the end of line in your file. While under Windows, an end of line amounts to a Carriage Return and a Linefeed character. Under Unix, this is different, so for a file written under Unix your programm will have to be adjusted.

Then, count every the successive number of the end of line character(s) and each time add this number minus 1 to a count. At the end, you will have the empty line count.

Upvotes: 0

Martin Ždila
Martin Ždila

Reputation: 3219

Try this:

final BufferedReader br = new BufferedReader(new StringReader("hello\n\nworld\n"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
  if (line.trim().isEmpty()) {
    empty++;
  }
}
System.out.println(empty);

Upvotes: 3

Related Questions