find dates in a string using regex in swift

You can use the NSRegularExpression class provided by Foundation to find dates in a string using regular expressions. Here's an example code snippet in Swift:

main.swift
let input = "Today is 2022-11-11 and tomorrow is 2022-11-12."
let pattern = "\\d{4}-\\d{2}-\\d{2}" // matches YYYY-MM-DD format

do {
    let regex = try NSRegularExpression(pattern: pattern)
    let matches = regex.matches(in: input, range: NSRange(input.startIndex..., in: input))
    
    for match in matches {
        let dateRange = Range(match.range, in: input)!
        let dateString = input[dateRange]
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        if let date = formatter.date(from: String(dateString)) {
            print(date)
        } else {
            print("Invalid date format: \(dateString)")
        }
    }
} catch {
    print("Regex error: \(error.localizedDescription)")
}
751 chars
23 lines

This code first defines the input string and the regular expression pattern to match dates in YYYY-MM-DD format. It then creates a NSRegularExpression object with the pattern and uses it to find matches in the input string.

For each match, the code extracts the substring that matches the pattern using the range returned by match.range. It then creates a DateFormatter object to convert the string to a Date, and prints the resulting date object if the conversion succeeds. If the conversion fails, it prints an error message.

gistlibby LogSnag