import Foundation
let pattern = #"^\$.*LOB.*00 &$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
$90TM020516 19002200&
$90LOB 0 0 0 7 10 &
$90LOB 25 0 0 6 10 &
$90LOB 57 0 0 6 10 &
$90LOB353 0 0 5 10 &
$90LOB 36 0 0 5 10 &
$90GPSA8 0 38281168 -77448376&
$90LOB276 0 0 5 10 &
$90LOB185 0 0 6 10 &
$90LOB197 0 0 6 00 &
$90LOB198 0 254 6 00 &
$90LOB197 0 254 6 00 &
RSSI $90LOB201 0 254 5 00 &
$90TM020516 19002300&
$90LOB194 0 254 5 00 &
$90LOB190 0 254 5 00 &
$90LOB185 0 254 5 00 &
$90LOB181 0 254 5 00 &
$90LOB187 0 254 5 00 &
$90LOB192 0 254 5 00 &
$90LOB195 0 254 5 00 &
$90LOB195 0 254 5 00 &
$90LOB191 0 254 5 00 &
$90LOB184 0 254 5 00 &
$90LOB177 0 254 5 00 &
"""#
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