import Foundation
let pattern = ##"""
(?xXmi)
(?:
(?# use non-capture for details in debugging)
(?:
(?<match>
(?# If quoted value)
(?<quot_char>(?<!\\)["'])
(?# Quoted content)
(?:
(?:
(?# Match as many characters that aren't quotation char)
(?# or escape char as possible. )
(?:(?:(?!\k<quot_char>|\\)).+)
(?:
(?# Match any/all escape chars that do not have the)
(?# quotation char following it. )
(?:(?:\\)*(?!\k<quot_char>))?
(?# If there is an escape char followed by the quotation)
(?# quotation char match them. )
(?:[\\]\k<quot_char>)?
)*?
)
)
(?<close_quot>\k<quot_char>)
|
(?# if simple token)
(?<basic>[^ \n]+)+
)
)
(?<trail_ws>[ ]+)?
)
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
-t1a1
-t2a1 -t2a2
-t3a1 -t3a2
-t4a1 Test1value -t4a2 test4a2value -t4a3 t4a3value
-t5a1EscQuot \'t5a1valueESQ\' -t5a2EscQuot \"t5a2valueEDQ\"
-t6a1 "t6a1value1DQWord1 t6a1value1DQWord1" -t6a2SQuot 't6a2value1SQWord1 t6a2value1SQWord2 t6a2value1SQWord3 '
-t7a1SQuotEmpty '' -t7a2DQuotEmpty ""
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"\n${match}"#
let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)
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