import Foundation
let pattern = #"^(?<year>\d{4})[-\/](?<month>0[1-9]|1[0-2])[-\/](?<day>0[1-9]|[1-2][0-9]|3[0-1])(?:[T\s](?:(?<hour>0[0-9]|1[0-9]|2[0-4]):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<nano>\d+))?))?(?:(?<offset>[Zz]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
2020-12-01T12:13:51.123+02:00
2020-12-01T12:13:51.123+0200
2020-12-01T12:13:51.123Z
2020-12-01T12:13:51.123
2020-12-01T12:13:51.123341512+02:00
2020-12-01T12:13:51.123341512+0200
2020-12-01T12:13:51.123341512Z
2020-12-01T12:13:51.123341512
2020-12-01T12:13:51+02:00
2020-12-01T12:13:51+0200
2020-12-01T12:13:51Z
2020-12-01T12:13:51
2020-12-01 12:13:51.123 +02:00
2020-12-01 12:13:51.123 +0200
2020-12-01 12:13:51.123Z
2020-12-01 12:13:51.123
2020-12-01 12:13:51.123341512 +02:00
2020-12-01 12:13:51.123341512 +0200
2020-12-01 12:13:51.123341512Z
2020-12-01 12:13:51.123341512
2020-12-01 12:13:51+02:00
2020-12-01 12:13:51+0200
2020-12-01 12:13:51Z
2020-12-01 12:13:51
2020-12-01+02:00
2020-12-01+0200
2020-12-01Z
2020-12-01
2020/12/01T12:13:51.123+02:00
2020/12/01T12:13:51.123+0200
2020/12/01T12:13:51.123Z
2020/12/01T12:13:51.123
2020/12/01T12:13:51.123341512+02:00
2020/12/01T12:13:51.123341512+0200
2020/12/01T12:13:51.123341512Z
2020/12/01T12:13:51.123341512
2020/12/01T12:13:51+02:00
2020/12/01T12:13:51+0200
2020/12/01T12:13:51Z
2020/12/01T12:13:51
2020/12/01+02:00
2020/12/01+0200
2020/12/01Z
2020/12/01
2039/15/23
2923/09/12
2023/23/51
2020-12-01T00:13:51
2020-12-01T01:13:51
2020-12-01T10:13:51
2020-12-01T19:13:51
2020-12-01T20:13:51
2020-12-01T24:13:51
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"$1-$2-$3"#
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