import Foundation
let pattern = #"(?:(?P<Day1>\d{1,2})(?:\W*(?P<Month1>[A-Z][a-z]*\b))|(?:(?P<Month2>[A-Z][a-z]*\b)\W*)(?:(?P<Day2>\d{1,2})(?:\b|th|st|nd))?|(?P<Month3>\d{1,2})\W+(?P<Day3>\d{1,2})|(?P<Month4>\d{1,2}))?\W+?(?P<Year>\d{2,4}(?=$|;))"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
04/20/2009
04/20/09
4/20/09
4/3/09
Mar-20-2009
Mar 20, 2009
March 20, 2009
Mar. 20, 2009
Mar 20 2009;
20 Mar 2009
20 March 2009
20 Mar. 2009
20 March, 2009
Mar 20th, 2009
Mar 21st, 2009
Mar 22nd, 2009
Feb 2009
Sep 2009
Oct 2010
6/2008
12/2009
2009
2010
"""#
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