Parsing strings with newline chars

When I received a command message over tcp from my security system, the message may contain multiple commands, separated by newline characters, such as this:

Command1
Command2
Command3

The documentation says

1.7 Terminator
(CR-LF) Message terminator. ASCII characters consisting of hexadecimal 0x0D and
0x0A. The 0x0A is optional. A message terminator may also use the 0x0A only.

In other words /n and/or /r

I’d like to be able to parse that string into individual messages, and then send each message through my code, such as this:

var String[] messageArray
rule "Security Message Received:
when
Item messageReceived changed
then
// put each message into the array
// foreach message in messageArray
// parse the message
// next
end

I’m on Ubuntu OH2, if that matters.

val commands = messageReceived.state.toString.split("\n|\r|\n\r")
commands.forEach[ cmd |
    // Process individual command
]

The split method on String takes a regular expression and returns an ordered list of Strings attached were delimited by the matched expression, exclusive (i.e. ith newlines will not be included.

2 Likes