import Foundation
let pattern = #"SMR_.*_(.*)_GRID_(?P<Model>[a-zA-Z]+)_.*"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
RV_Exp_CX_GRID_08OCT18.dat
RV_Exp_JT_GRID_07NOV18.dat
RV_Exp_OPEL_WB_GRID_21NOV18.dat
RV_Ref_U_GRID_07NOV18.dat
SMR_Exp_CX_GRID_D_11OCT18txt
SMR_Exp_CX_GRID_E_30JUL18txt
SMR_Exp_CX_GRID_JS_07AUG18txt
SMR_Exp_CX_GRID_JT_17SEP18txt
SMR_Exp_GRID_D_07NOV18txt
SMR_Exp_GRID_E_05OCT18txt
SMR_Exp_GRID_JS_08JAN19txt
SMR_Exp_GRID_JT_07NOV18txt
SMR_Ref_GRID_D_07NOV18txt
SMR_Ref_GRID_E_05OCT18txt
SMR_Ref_GRID_JS_08JAN19txt
SMR_Ref_GRID_JT_07NOV18txt
SMR_WB_Exp_GRID_D_14NOV18txt
SMR_WB_Exp_GRID_JS_20FEB19txt
SMR_WB_Exp_GRID_JT_14NOV18txt
"""#
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