import Foundation
let pattern = #"^([a-zA-Z0-9].+?)(\s+)((?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29))(\s+)((0?9|1[0-9]|2[01]):00~(1[0-9]|2[0-2]):00)(\s+)([A-D])(\sC)"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"U001 2020-01-01 9:00~22:00 A C"#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #""#
let lookupRange = (testString as NSString).range(of: pattern, options: .regularExpression, range: stringRange)
if lookupRange.intersection(stringRange) != nil {
let result = regex.stringByReplacingMatches(in: testString, range: lookupRange, withTemplate: substitutionString)
print(result)
} else {
print("No matches were found.")
}
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