Processing multiline reports formatted with ‘\r\n’

Occasionally, report text may contain lines terminated with carriage return ‘\r’ and new line ‘\n’ characters. Both interfere with HL7 message integrity.

What if on top of it Report Message also has segment termination incorrect, showing ‘\r\n’ instead of single ‘\r’?

So how do we process such message?

Below is brilliant 3 steps (and hardly 4 code lines) solution suggested by Eric.

First we replace all ‘\r\n’ with ‘\n’.

Next we find segment names which can consist of 3 letters %u%u%u or of a letter and digits %u[%u%d][%u%d] followed by pipe character %u[%u%d][%u%d]|, and fix them one by one by replacing ‘\n’ with ‘\r’.

Last step is replacing ‘\r’ in report text itself with escaped presentation of ‘\r\n’ which is ‘\\X0D\\\\X0A\\’

Note: Backslashes must be escaped: so ‘\’ becomes ‘\\’

Here’s a copy of the code you can copy and paste:

InSchema = 'example/transform_inbound.vmd'
OutSchema = 'example/transform_inbound.vmd'

function main(Data)
 -- Normalize line-ends.
 Data = Data:gsub('\r\n','\n'):gsub('\r','\n')

 -- Correct segment delimiters.
 Data = Data:gsub('\n(%u[%u%d][%u%d]|)', '\r%1')
 Data = Data:gsub('\n$', '\r')

 -- Escape newlines inside delimiters
 Data = Data:gsub('\n', '\\X0D\\\\X0A\\')

 local In = hl7.parse{vmd=InSchema, data=Data}

 print(In.OBX)

end

Here is what  our original HL7 message looks like:

and here is what Report text looks like with ‘\r\n’ replaced with escaped presentation:

Below is sample vmd file to use with this code, but you can use any of your own vmd files that describes your test message.

example_transform_inbound.vmd

… and Lorem Ipsum test message:

ORU R01with CR and LF.txt

Leave A Comment?