import Foundation
let pattern = #"(?:^(R)\|(\d+)\|\^*([^|]*)\|([^|]*)\|(?:([^|]*)\|)?.*$)|(?:^(P)\|(\d+)\|\|(\d+).*$)"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = #"""
P|1||322061||^|||U
O|1||138||||||||||||O
R|1|^^^BE(B)||mmol/L||C||||||20150819144937
R|2|^^^BEecf||mmol/L||C
R|3|^^^Ca++|1.17|mmol/L
R|4|^^^Ca++(7.4)||mmol/L||C
R|5|^^^HCO23-||mmol/L||C
R|6|^^^HCO3std||mmol/L||C
R|7|^^^K+|5.0|mmol/L
R|8|^^^Na+|140|mmol/L
R|9|^^^SO2c||%||C
R|10|^^^TCO2||mmol/L||C
R|11|^^^THbc||g/dL||C
R|12|^^^Temp|37.0|C
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression