Currently I'm using StringEscapeUtils.escapeJava()
from Apache Commons, but this is marked as deprecated since 3.6 and the suggestion is to move to the commons-text
package. Since I'm currently not depending on that, and don't feel the need to add another dependency for just this one package, I was looking into the escaping functionality that one of my other included libraries (Guava) provides.
However, I could not find an equivalent to the escapeJava()
method. Since Guava seems to work a little differently, I was wondering if someone could point out how I could achieve the same result using Guava? (or using non-deprecated classes from commons-lang3
)
Since I couldn't find any decent alternatives within guava, I gave it another go using the StringUtils
class from lang3
. I made a small utility function that escapes newlines and tab characters. Suggestions welcome, but this will do for now.
public static String escapeForLogs(String input) {
return org.apache.commons.lang3.StringUtils.replaceEach(
input,
new String[] { "\r\n", "\r", "\n", "\t" },
new String[] { "\\\\n", "\\\\n", "\\\\n", "\\\\t" }
);
}
I run the following tests on it:
@Test
public void testEscapeForLogs() {
assertEquals("without linebreaks/tabs stays the same", "lala", e scapeForLogs("lala"));
assertEquals("empty string is fine", "", escapeForLogs(""));
assertEquals("newline gets escaped", "\\\\n", escapeForLogs("\n"));
assertEquals("two newlines", "\\\\n\\\\n", escapeForLogs("\n\n"));
assertEquals("tab", "\\\\t", escapeForLogs("\t"));
assertEquals("return carridge gets escaped", "\\\\n", escapeForLogs("\r"));
assertEquals("return carridge+newline gets converted", "\\\\n", escapeForLogs("\r\n"));
assertEquals("newline before cr+nl", "\\\\n\\\\n", escapeForLogs("\n\r\n"));
assertEquals("2 cr+nl", "\\\\n\\\\n", escapeForLogs("\r\n\r\n"));
assertEquals("some combination", "lala\\\\nlalala\\\\n\\\\nla\\\\tla", escapeForLogs("lala\nlalala\n\nla\tla"));
}