Swift Regex literal are compatible with Python, Perl and many others.
// Regex literals
let digits = /\d+/
// digits: Regex<Substring>
Syntax for Regex literals
Each language has its own “flavor” for (literal) regex syntax.
The Swift implementation is closely related to ICU (see ICU documentation).
- Swift Regex literals start and end with
/
- Strongly typed capturing groups
- literals infer the strong types for all the internal captures
Extended Delimiters
Syntax:
- starts with
#/
and ends with/#
- See: Meet Swift Regex WWDC22 at 10:45
- See: WWDC22 Swift Regex: Beyond the Basics at 8:40
When using extended delimiters:
- slashes do not need to be escaped
- allows non-semantic whitespaces:
- whitespace is ignored
- below
date
is a named capture
let regex = #/
(?‹date> \d{2} / \d{2}/ \d{4)
(?<middle> \P{currencySymbol}+)
(?‹currency> \p{currencySymbol})
/#
// Regex<(Substring, date: Substring, middle: Substring, currency: Substring)>