Regex and String Processing
42.1 Swift Regex (Swift 5.7+)
let input = "Order #A123 shipped on 2025-10-24 to [email protected]"
// Regex literal (compile-time checked)
if let match = input.firstMatch(of: /(\d{4})-(\d{2})-(\d{2})/) {
let (_, year, month, day) = match.output // typed captures (Substring)
print(year, month, day)
}
// Named captures
let datePattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
if let m = input.firstMatch(of: datePattern) { print(m.year, m.month) }
input.contains(/\d+/)
input.matches(of: /\d+/).map(\.output) // all matches
input.replacing(/\d/, with: "#")
input.split(separator: /\s+/)
try /\w+@\w+\.\w+/.wholeMatch(in: "[email protected]")
let runtimeRegex = try Regex("[a-z]+") // runtime-constructed regex42.2 RegexBuilder (DSL)
Swift Regex handles Unicode correctly (grapheme-aware), and you can mix in Foundation parsers (dates, numbers, currencies).
import RegexBuilder
let amount = Reference(Double.self)
let currencyRegex = Regex {
"$"
Capture(as: amount) {
OneOrMore(.digit)
Optionally {
"."
Repeat(.digit, count: 2)
}
} transform: { Double($0)! }
}
if let match = "Total: $42.50".firstMatch(of: currencyRegex) {
print(match[amount]) // 42.5 (typed!)
}
let dateParser = Regex {
Capture { One(.date(.numeric, locale: Locale(identifier: "en_US"), timeZone: .gmt)) } // Foundation parsers in regexes
}