zneo
zneo

Reputation: 598

Delete blank lines at end of text

I'm trying to create a method, that deletes empty lines at the end of a string:

public static String deleteBlankLinesAtEnd(String input)
{
    input = trimToEmptyString(input);
    return input.replaceFirst("\\n{2,}\\z", "");
}

However, it seems to also delete empty lines in the beginning of the input.

I got a little unit test:

@Test
public void testDeleteBlankLinesAtEnd()
{
    assertEquals("hej", TextUtils.deleteBlankLinesAtEnd("hej\n\n"));
    assertEquals("hej\nhej", TextUtils.deleteBlankLinesAtEnd("hej\nhej\n\n"));
    assertEquals("hej\n\nhej", TextUtils.deleteBlankLinesAtEnd("hej\n\nhej\n\n"));
    assertEquals("\n\nhej\n\nhej", TextUtils.deleteBlankLinesAtEnd("\n\nhej\n\nhej\n\n"));
}

The 3 first runs fine, the last one fails.

Update: Of course, the trimToEmptyString() was my problem, since it also trims the beginning..

public static String trimToEmptyString(String input)
{
    if (input == null)
    {
        return "";
    }
    return input.trim();
}

So everything with the regex, was working fine.

Upvotes: 0

Views: 1769

Answers (3)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

The regex looks OK; I suspect there's a problem with trimToEmptyString().

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

How about to replace all blank lines including lines full of spaces.

input.replaceFirst("\\n\\s+$", "\n")

Upvotes: 1

npinti
npinti

Reputation: 52185

You could do something like so:

public static String deleteBlankLinesAtEnd(String input)
{
    input = trimToEmptyString(input);
    return input.replaceFirst("\\n{2,}\\z$", "");
}

The $ should instruct the regex to match anything just before the end of the string. In this case, it should match any new lines which are just prior to the end of the string.

Upvotes: 1

Related Questions