import Foundation
let pattern = #"(?:device_model = \['?|data9 = \['|, ')([^'\],\r\n]*)(?=.*\r?\n(?:[ \t]*\[.*\r?\n)*?[ \t]*(?:current_version = ')(.*))"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
"// Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
main = {
data1 = value
data2 = value
model_types = [
// Type 1,2,3
{
device_model = ['type1_v1', 'type1_v2']
current_version = '1.2.34.56'
},
{
device_model = ['type2_v1', 'type2_v2']
data3 = value
current_version = 'type2911-54.32'
},
{
device_model = ['type_v3'] // misc data
current_version = '1.2.3-t35_098'
},
// Type 4 and 5
{
device_model = ['type4_v1', 'type4_v2']
data4 = value
data5 = value
current_version = '6.6.9-TY4_998'
},
{
device_model = ['type5_v1', 'type5_v2', 'type5_v3']
data6 = value
current_version = '1.5.6-TY5_354'
data7 = value
},
// Type 6 and Wifi1
{
device_model = ['type6_v1']
current_version = '1.4.65-20240220'
},
{
device_model = ['type6_w1']
current_version = '1.2.3'
},
// Type 7 and Wifi2
{
device_model = ['type7_v1']
data8 = value
current_version = '2.3.6-9'
children = [{
data9 = ['value']
current_version = '4.8.1'
}]
},
{
device_model = ['type7_w2']
data10 = value
current_version = '5.1.4-b'
children = [{
data9 = ['value']
current_version = '8.4.1'
}]
},
// Type 8
{
device_model = ['type8_v1']
current_version = 'ty8-87.41'
data11 = value
},
{
device_model = ['type8_v2']
current_version = 'ty8-87.41'
},
// Type 9
{
device_model = ['type9_v1]
current_version = 'ty9-14.9-v198'
},
// Type 10
{
device_model = ['type10_v1', 'type10_v2']
current_version = '2.2.3.110ty'
},
]
}
"
"""#
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