import Foundation
let pattern = #"([A-Z0-9]{4})"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
; Message Number
; | Time Offset (ms)
; | | Type
; | | | ID (hex)
; | | | | Data Length
; | | | | | Data Bytes (hex) ...
; | | | | | |
;---+-- ----+---- --+-- ----+--- + -+ -- -- -- -- -- -- --
1) 2.0 Rx 0400 8 01 5A 01 57 01 D2 A6 02
2) 8.6 Rx 0500 8 02 C1 02 C9 02 BE 02 C2
3) 36.2 Rx 0401 8 01 58 01 59 01 01 01 01
4) 41.7 Rx 01C4 8 27 9C 64 8C 00 03 E8 08
5) 43.1 Rx 0501 8 02 C0 02 C1 02 C6 02 C0
6) 62.7 Rx 01C2 8 27 9C 60 90 00 0F 04 08
"""#
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