Remove multi-line line end whitespace

Posted by ChenRiang on June 4, 2021

Today, I bump into a problem when fixing some failed unit test.

Long story short, I need to compare returned multiline string from class A and for some reason it randomly added a whitespace in each line end. This caused the unit test failed.

Solution

Found this solution which stripe out the line end whitespace using regrex.

1
2
3
4
5
6
7
8
9
10
11
private final Pattern LINE_END_SPACES = Pattern.compile(" +\$", Pattern.MULTILINE);

public String stripLineEndSpaces(String str) {
    return LINE_END_SPACES.matcher(str).replaceAll("");
}

@Test
public void testAbc()
    String testObject  = "123 \n abc ";
    assertEquals("123\n abc", stripLineEndSpaces(testObject));
}


Reference

stackoverflow