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.