Java String split fails at "\n"

Viewed 139

In a apache camel processor methos I am trying to split a string, which was delivered from an Apache Kafka message broker as JSON. The split routine looks as follows:

String[] messageLines = new String[0];

if (messageBody.contains("\\n")) {
    messageLines = messageBody.split("\\n");
} else {
    messageLines = messageBody.split("\n");
}

In the debugger, the "messageBody" string looks like this:

"deviceName (string:1) -> TEST\nintValue (int:1) -> 123\ndoubleValue (double:1) -> 12.345\nacquisitionStamp (long:1) -> 1592468678231250944\nintArrayValue (int[]:10) -> [1,2,3,4,5,6,7,8,9,10]"

The code runs into the if (messageBody.contains("\\n")) {... part, but the .split("\\n") returns an array with one entry (the complete messageBody string) only. Same happens is I use .split("\n"). What is wrong here?

2 Answers

String.split() accepts a regex as argument. In order to match a literal backslash (\) in a string, you need 4 backslashes (\\\\) in your regex.

The backslash needs to be escaped once for the regex, and then the resulting two backslashes are escaped again for use in the string.

For your example, it would be:

messageLines = messageBody.split("\\\\n");

Please use StringTokenizer class to split(tokenise) the string instead of String.split(). StringTokenizer st = new StringTokenizer(str, "\n") to break the string in the new line.

or StringTokenizer st = new StringTokenizer(str, "\\n") to break it when there is '\n'

Related