import Foundation
let pattern = #"(?:.*?^0\,){1}"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
"REC01",
"Recipe1",
10,
"",
"",
" ",
2000,
"0101",
" ",
" ",
"126",
"REC01",
" ",
0,
0,
5,
38.182,"11200","Ingredient1"," "," ","1",
12.121,"11800","Ingredient2"," "," ","1",
27.475,"30910","Ingredient3"," "," ","1",
2.020,"26200","Ingredient4"," "," ","1",
20.202,"C01","Ingredient5"," "," ","1",
0,
"REC02",
"Recipe2",
10,
"13/04/21",
"13/04/21",
" ",
1000,
"0101",
" ",
" ",
"17",
"REC02",
" ",
0,
0,
3,
61.600,"11200","Ingredient1"," "," ","1",
23.400,"30910","Ingredient3"," "," ","1",
15.000,"BR-F01","Ingredient6"," "," ","1",
0,
"REC03",
"Recipe3",
10,
"19/03/21",
"19/03/21",
" ",
1000,
"0103",
" ",
" ",
"28",
"REC03",
" ",
0,
0,
9,
64.450,"11200","Ingredient1"," "," ","1",
12.700,"30910","Ingredient3"," "," ","1",
2.000,"20600","Ingredient7"," "," ","1",
12.000,"27220","Ingredient8"," "," ","1",
0.320,"584","Ingredient9"," "," ","1",
0.830,"588","Ingredient10"," "," ","1",
0.050,"599","Ingredient11"," "," ","1",
0.040,"600","Ingredient12"," "," ","1",
7.610,"585","Ingredient13"," "," ","1",
0,
"""#
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