import Foundation
let pattern = #"""
(?<!d)(?:
(?:(?:0?[1-9]|[12]\d)|3[01])\s?[./:-][\s.]?(?:0?[13578]|1[02]|J(?:an(?:uar)?|uli?)|M(?:ärz?|ai)|Aug(?:ust)?|Dez(?:ember)?|Okt(?:ober)?)\s?(?:[./:-][\s.]?)?[1-9]\d\d\d|
(?:(?:0?[1-9]|[12]\d)|30)\s?[./:-][\s.]?(?:0?[13-9]|1[012]|J(?:an(?:uar)?|u[nl]i?)|M(?:ärz?|ai)|A(?:pr(?:il)?|ug(?:ust)?)|Sep(?:tember)?|(?:Nov|Dez)(?:ember)?|Okt(?:ober)?)\s?(?:[./:-][\s.]?)?[1-9]\d\d\d|
(?:0?[1-9]|[12]\d)\s?[./:-][\s.]?(?:0?2|Fe(?:b(?:ruar)?)?)\s?(?:[./:-][\s.]?)?[1-9]\d(?:[02468][048]|[13579][26])|
(?:0?[1-9]|[12][0-8])\s?[./:-][\s.]?(?:0?2|Fe(?:b(?:ruar)?)?)\s?(?:[./:-][\s.]?)?[1-9]\d\d\d
)(?!\d)
"""#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .allowCommentsAndWhitespace])
let testString = #"""
12.12.2021
09. Juni 1997
01.Aug.1995
27.06. 1997
29.02.1996
21. 01. 1999
28.05. 1996
07..4..1995
20:03:1998
9.4.1997
14 .03 - 1995
Month regex is tested at https://regex101.com/r/tClRRs/2
(?:J(?:an(?:uar)?|u[nl]i?)|Fe(?:b(?:ruar)?)?|M(?:ärz?|ai)|A(?:pr(?:il)?|ug(?:ust)?)|Sep(?:tember)?|(?:Nov|Dez)(?:ember)?|Okt(?:ober)?)
Taking out Feb: (?:J(?:an(?:uar)?|u[nl]i?)|M(?:ärz?|ai)|A(?:pr(?:il)?|ug(?:ust)?)|Sep(?:tember)?|(?:Nov|Dez)(?:ember)?|Okt(?:ober)?)
"""#
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