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.swift751 chars23 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