import Foundation
let pattern = #"[0-9]{2}\/[0-9]{2}\/[0-9]{4}"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
Valid dates:
01/04/2020
20/01/2019
25/12/1950
30/07/2021
31/08/1919
01/01/1729
10/05/2000
15/10/2049
Invalid dates:
001/04/1900
01/004/1900
90/04/1900
33/04/1900
01/13/1900
01/04/19000
00/04/1900
01/00/1900
1/4/00
1/04/1900
10/4/1900
10/04/00
///
/04/1900
01//1900
01/04/
01/04/1900
This is the date: 01/04/1900
01.04.1900
01-04-1900
"""#
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