using System.Collections.Generic;
using System.Text.RegularExpressions;
private static List<string> segments;
public static void SplitHL7Message(string message)
segments = new List<string>(message.Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries));
public static string GetField(string accessor)
string[] accessor_elements = accessor.Split(new[] { '.' });
string segmentId = accessor_elements[0];
accessor_elements = accessor_elements.Skip(1).ToArray();
string segment = segments.Find(s => s.StartsWith(segmentId));
if (segment == null) return null;
var headerSegment = segments[0];
char fieldSeparator = headerSegment[3];
char componentSeparator = headerSegment[4];
char repetitionSeparator = headerSegment[5];
char escapeCharacter = headerSegment[6];
char subcomponentSeparator = headerSegment[7];
string[] fields = segment.Substring(segmentId.Length + 1).Split(fieldSeparator);
fields = new string[] { segmentId }.Concat(fields).ToArray();
if (accessor_elements.Length == 0)
int repetitionIndex = -1;
var fieldRegex = new Regex(@"(\d+)(?:\[(\d+)\])?");
var match = fieldRegex.Match(accessor_elements[0]);
fieldIndex = int.Parse(match.Groups[1].Value);
repetitionIndex = match.Groups[2].Value != "" ? int.Parse(match.Groups[2].Value) - 1 : -1;
if (fieldIndex >= fields.Length)
string field = fields[fieldIndex];
if (repetitionIndex >= 0) {
string[] repetitions = field.Split(repetitionSeparator);
if (repetitionIndex >= repetitions.Length)
field = repetitions[repetitionIndex];
if (accessor_elements.Length == 1)
string currentLevel = field;
for (int i = 1; i < accessor_elements.Length; i++)
string currentElement = accessor_elements[i];
int componentIndex = int.Parse(currentElement) - 1;
string[] components = currentLevel.Split(componentSeparator);
if (i == accessor_elements.Length - 1)
if (componentIndex >= components.Length)
currentLevel = components[componentIndex];
if (componentIndex >= components.Length)
currentLevel = components[componentIndex];
public static void Main(string[] args)
string message = @"MSH|^~\&|TTM||host||20230727170458+0100||SSU^U03^SSU_U03|sQELfcfwyCH2|P|2.5.1|||NE|AL||Unicode UTF-8|||LAB26^IHE~RQPO^ROCHE
EQU|TTM^ROCHE~1234-56^ROCHE|20230727170458|OP
SAC|||SID||PUUID|||I|HITACHI_917_R^^99ROC|CID|CPOS||||SIO^^99ROC|||||||||||OCAP^^HL70381
SPM|1|SID||“”|||||||P|||||||||||||NCFU^^HL70493|||SCT^^99ROC";
SplitHL7Message(message);
Console.WriteLine(GetField("MSH"));
Console.WriteLine(GetField("MSH.1"));
Console.WriteLine(GetField("MSH.2"));
Console.WriteLine(GetField("MSH.6"));
Console.WriteLine(GetField("MSH.8"));
Console.WriteLine(GetField("MSH.8.2"));
Console.WriteLine(GetField("EQU.1"));
Console.WriteLine(GetField("EQU.1[1].2"));
Console.WriteLine(GetField("EQU.1[1].1"));
Console.WriteLine(GetField("EQU.1[2]"));
Console.WriteLine(GetField("EQU.1.2"));