import Foundation
let pattern = ##"""
(?x) # invoke extended (aka free-spacing) mode
^ # match beginning of the string
[^"\n]* # match zero or more chars other than line terminators and double-quotes
" # match a double-quote
[^"\n]* # match zero or more chars other than line terminators and double-quotes
(?<! # begin a negative lookbehind
\ # match a space
| # or
\\n # match a backslash followed by n
) # end negative lookbehind
" # match a double-quote
\n # match a newline
\ * # match zero or more spaces
" # match double-quote
[^ "\n] # match a character other than a space, double-quote or newline
[^"\n]* # match zero or more chars other than line terminators and double-quotes
" # match a double-quote
\n? # optionally match a newline
$ # match end of string
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
a c"d1 %"
"&g i"
"9"
"&"
d a"fe "
"3h j"
a c"d1 \n"
"&g i"
a"de f%x"
" &12 "
#3 does not match due to space preceding second double-quote
#4 does not match due to a backslash followed by n preceding second double-quote
#5 does not match due to backslash followed by n following third double-quote
#5 does not match due to space following third double-quote
"""##
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