import Foundation
let pattern = #"(?s)\nclass\s(.*?)(?=\().*?model\s=\s(.*?)\n.*?(?=fields.*?\((.*?)\)).*?(?=write_once_fields.*?\((.*?)\)).*?(?=required_fields.*?\((.*?)\))"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = ##"""
import stuff
class ITEM1(BaseSerializer):
'''docstring'''
profile_id = None
house_id = None
# synopsis = ModelIDListField(source='synopsis', serializer=NotificationSerializer)
class Meta:
'''docstring'''
# model = Null
model = ITEM2
fields = (ITEM3)
# write_once_fields = (Null)
write_once_fields = (ITEM4)
required_fields = (ITEM5)
depth = 1
class ITEM1(HouseUserSerializer):
# synopsis = ModelIDListField(source='synopsis')
class Meta:
# model = Null
model = ITEM2
fields = (ITEM3)
required_fields = (ITEM5)
depth = 1
"""##
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