import Foundation
let pattern = #"HARRY((?:(?:(?!HARRY|DIVISION 3).|[\r\n])*?)DIVISION 3)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
S3007/0011
20150590824
HARRY MOSES
F
32
DIVISION 4
CIV-'F' HIST-'D' GEO-'F' KISW-'D' ENGL-'D' PHY-'F' CHEM-'F' BIO-'F' B/MATH-'F'
S3007/0012
20151514797
HARRY MORGAN
F
26
DIVISION 3
CIV-'D' HIST-'C' GEO-'D' KISW-'C' ENGL-'C' PHY-'F' CHEM-'F' BIO-'D' B/MATH-'F'
S3007/0013
20151514798
HAPPINESS DEOGRATIAS
F
34
DIVISION 0
CIV-'F' HIST-'F' GEO-'F' KISW-'D' ENGL-'F' PHY-'F' CHEM-'F' BIO-'F' B/MATH-'F
"""#
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