import Foundation
let pattern = #"^@ heading2$[\s\S]*?^(?:field2: \"?((?<=\")[^"\\]*(?:\\.[^"\\]*)*(?=\"$)|(?<!\").*(?!\")$)\"?$|)?$[\s\S]*?(?=@ [^\s]*?|\Z)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
@ heading1
field1: "single-line strings are quoted only sometimes."
field2: "strings that span
multiple lines
are always quoted."
field3: this single-line string is unquoted.
@ heading2
field1: field names can be repeated among headings.
field2: "Regex is harder when I add an
@ in a multi-line string, or if I add
backslash-escaped characters like \" and \'.
What happens if I have an empty line in a string?
Also,
[this line]
isn't actually a section."
field3: this field comes after field2
[sectionname]
field1: the same field name under a different section.
[anothersection]
field1: a second section under the same heading
field4: field number four
@ heading3
field1: value value value value value
field2: "quoted string
quoted string
quoted string"
unique: unique field name
"""#
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