import Foundation
let pattern = #"""
^ \h*+
(?<VOTERNO> [0-9]+ ) \h+
(?<SURNAME> \S+ (?>\h\S+)*? ) \h{2,}
(?<OTHERNAMES> \S+ (?>\h\S+)*? ) \h{2,}
(?<DOB> [0-9]{2}-[0-9]{2}-[0-9]{4} ) \h+
(?<SEX> [FM] ) \h+
(?<APPID_RECNO> [0-9A-Z/]+ ) \h+
(?<VILLAGE> \S+ (?>\h\S+)* )
\h* $
"""#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .allowCommentsAndWhitespace])
let testString = #"""
NATIONAL VOTERS' REGISTER
ELECTORAL COMMISSION ACT, CAP(140)
NVR TEXT REGISTER FOR GENERAL ELECTIONS 2015/2016
DISTRICT : 12 JOI
CONSTITUENCY : 035 GRGR RT
SUB-COUNTY : 11 GHT
PARISH : 01 ATZ
POLLING STATION : 01 OT
TOTAL: 398
NO OF PAGES : 9
THE REPUBLIC
NATIONAL VOTERS' REGISTER
ELECTORAL COMMISSION ACT, CAP(140)
NVR TEXT REGISTER FOR GENERAL ELECTIONS 2015/2016
DISTRICT : 12 JOI PARISH : 01 ATZ
CONSTITUENCY : 035 GRGR RT POLLING STATION : 01 OT
SUB-COUNTY : 11 GHT
VOTER NO SURNAME OTHERNAMES DOB SEX APPID/RECEIPT NO VILLAGE
57534676 AAA BBB 01-01-1965 M 0323830000V0C/CM5607 ABC
53276273 CCC DDD 28-07-1981 M 1074620203FUX/CM9007 TTR RR
TOTAL: 398 PAGE : 1 OF 9
THE REPUBLIC
NATIONAL VOTERS' REGISTER
ELECTORAL COMMISSION ACT, CAP(140)
NVR TEXT REGISTER FOR GENERAL ELECTIONS 2015/2016
DISTRICT : 12 JOI PARISH : 01 ATZ
CONSTITUENCY : 035 GRGR RT POLLING STATION : 01 OT
SUB-COUNTY : 11 GHT
VOTER NO SURNAME OTHERNAMES DOB SEX APPID/RECEIPT NO VILLAGE
53390750 EEE FFF 18-04-1978 F 13238200006Z6/CF8507 TTR
60977834 GGG HHH 25-05-1979 F 1176520002RK4/CF1907 BREH
"""#
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