Regex literals and RegexBuilder
suggest changeSwift 5.7 added a native regular expression type, Regex<Output>, to the standard library. You can create one in three ways:
- a regex literal like
/\d+/, which the compiler parses and checks, try Regex(someString), for a pattern that is only known at run time,- the RegexBuilder DSL, which describes the pattern with Swift code.
All three produce the same Regex type and work with the same string methods: firstMatch(of:), wholeMatch(of:), matches(of:), replacing(_:with:), split(separator:) and more.
The big difference from NSRegularExpression is that captures are typed. The regex /(\d{4})-(\d{2})/ has the type Regex<(Substring, Substring, Substring)>, so match.1 is a Substring and match.3 is a compile error. There are no NSRange values and no as NSString casts, and matching works on Characters, not UTF-16 code units.
The examples were compiled and run with Swift 6.4 on Windows, in the Swift 6 language mode:
swiftc -swift-version 6 main.swift
Regex needs Swift 5.7 or later. On Apple platforms it also needs macOS 13 / iOS 16 or later.
In the Swift 5 language mode, bare /.../ literals are off by default, because they could break existing code that uses / as an operator. Turn them on with the -enable-bare-slash-regex compiler flag, or in Package.swift with swiftSettings: [.enableUpcomingFeature("BareSlashRegexLiterals")]. The extended #/.../# form described below works in every mode.
Regex literals and typed captures
A regex literal is written between slashes. Each match has an output property, and its type depends on the capture groups:
let line = "Order 1042 shipped on 2026-10-18 to Berlin"
let digits = /\d+/
if let match = line.firstMatch(of: digits) {
print(match.output)
print(type(of: match.output))
}
let date = /(\d{4})-(\d{2})-(\d{2})/
if let match = line.firstMatch(of: date) {
print(match.0)
print(match.1, match.2, match.3)
print(type(of: match.output))
}
Output:
1042
Substring
2026-10-18
2026 10 18
(Substring, Substring, Substring, Substring)
A regex without groups has the output Substring, which is the whole match. With groups the output is a tuple: element 0 is the whole match and 1, 2, ... are the groups. match.1 is a shortcut for match.output.1.
Because the compiler parses the literal, mistakes are caught at build time:
let bad = /(\d+/
let date = /(\d{4})-(\d{2})/
if let m = "2026-10".wholeMatch(of: date) {
print(m.3)
}
error: cannot parse regular expression: expected ')'
error: value of type 'Regex<(Substring, Substring, Substring)>.Match' has no dynamic member '3' using key path from root type '(Substring, Substring, Substring)'
Named and optional captures
Name a group with (?<name>...) and it becomes a labeled tuple element. A group that may not take part in a match (because it's inside ? or one side of |) is captured as Substring?:
let line = "Order 1042 shipped on 2026-10-18 to Berlin"
let date = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
if let m = line.firstMatch(of: date) {
print(m.year, m.month, m.day)
print(type(of: m.output))
print(line[m.range])
}
// optional group -> optional capture
let version = /v(\d+)(?:\.(\d+))?/
for s in ["v6", "v6.2"] {
if let m = s.wholeMatch(of: version) {
print(m.1, m.2 as Any)
}
}
Output:
2026 10 18
(Substring, year: Substring, month: Substring, day: Substring)
2026-10-18
6 nil
6 Optional("2")
m.range is a Range<String.Index> that you can use to slice the original string. The captures are Substrings, so they share storage with the input. Convert them with String(...) if you keep them around.
Extended delimiters
Put the literal between #/ and /# to write / without escaping it. If the extended literal spans several lines, whitespace in it is ignored and you can use # comments, which is useful for long patterns:
let url = #/
(?<scheme> https?) ://
(?<host> [^/:]+ )
(?: : (?<port> \d+ ) )?
(?<path> /\S* )?
/#
if let m = "see https://swift.org:443/blog/ for news".firstMatch(of: url) {
print(m.scheme, m.host, m.port ?? "-", m.path ?? "-")
}
print("a/b/c".split(separator: #/\//#))
Output:
https swift.org 443 /blog/
["a", "b", "c"]
Matching: firstMatch, wholeMatch, prefixMatch, matches
The three single-match methods differ in how much of the string must match:
wholeMatch(of:)needs the regex to match the entire string. Use it for validation.firstMatch(of:)finds the first match anywhere in the string.prefixMatch(of:)needs the match to start at the beginning of the string.
All of them return an optional Regex<Output>.Match. To find every match, use matches(of:). To get just the ranges, use ranges(of:):
let id = /[A-Z]{3}-\d{4}/
print("ABC-1234".wholeMatch(of: id) != nil) // whole string must match
print("ticket ABC-1234".wholeMatch(of: id) != nil)
print("ticket ABC-1234".firstMatch(of: id)?.output ?? "none")
print("ABC-1234 done".prefixMatch(of: id)?.output ?? "none")
print("ticket ABC-1234".contains(id))
print("ABC-1234 done".starts(with: id))
let log = "GET /a 200, GET /b 404, POST /c 500"
for m in log.matches(of: /(GET|POST) (\S+) (\d{3})/) {
print(m.1, m.2, Int(m.3)!)
}
print(log.ranges(of: /\d{3}/).map { log[$0] })
Output:
true
false
ABC-1234
ABC-1234
true
true
GET /a 200
GET /b 404
POST /c 500
["200", "404", "500"]
With wholeMatch you don't need ^ and $ anchors.
Replacing, splitting and trimming
The string algorithms that take a String separator also accept a regex:
let text = "Call 555-1234 or 555-9876 today"
print(text.replacing(/\d{3}-\d{4}/, with: "XXX-XXXX"))
print(text.replacing(/\d{3}-\d{4}/, with: "XXX-XXXX", maxReplacements: 1))
// closure gets the typed match
let swapped = text.replacing(/(\d{3})-(\d{4})/) { m in
"\(m.2)-\(m.1)"
}
print(swapped)
let csv = "alpha, beta,gamma , delta"
print(csv.split(separator: /\s*,\s*/))
var path = "///usr//local/bin"
path.trimPrefix(/\/+/)
print(path)
print(" indented".trimmingPrefix(/\s+/))
var s = "a1b22c333"
s.replace(/\d+/, with: "#")
print(s)
Output:
Call XXX-XXXX or XXX-XXXX today
Call XXX-XXXX or 555-9876 today
Call 1234-555 or 9876-555 today
["alpha", "beta", "gamma", "delta"]
usr//local/bin
indented
a#b#c#
The replacement string is used as is: $1 in it is not a backreference. To use parts of the match, pass a closure. It gets the typed Match, so m.1 and m.2 are checked by the compiler. Compare this with the template strings in Replacing Substrings.
replacing returns a new string. replace changes the string in place.
Regex in switch statements
The Regex proposal (SE-0357) described a ~= operator so that a regex could be used as a case pattern, but it was never added to the standard library. In Swift 6.4 this still doesn't compile:
switch input {
case /\d+/: // error
...
}
error: expression pattern of type 'Regex<Substring>' cannot match values of type 'String'
It takes three lines to add the operator yourself. Use wholeMatch so that a case matches the entire value, the way other case patterns do:
func ~= <Output>(regex: Regex<Output>, input: String) -> Bool {
input.wholeMatch(of: regex) != nil
}
func classify(_ input: String) -> String {
switch input {
case /\d+/:
return "integer"
case /\d+\.\d+/:
return "decimal"
case /[a-z_][a-z0-9_]*/:
return "identifier"
default:
return "unknown"
}
}
for s in ["42", "3.14", "user_id", "42abc", "x 1"] {
print(s, "->", classify(s))
}
Output:
42 -> integer
3.14 -> decimal
user_id -> identifier
42abc -> unknown
x 1 -> unknown
A case pattern can't bind the captures. When you need them, use if let m = input.wholeMatch(of: ...) instead.
Options
Options are methods on Regex that return a modified regex:
let text = """
Name: Alice
name: bob
NAME: Carol
"""
// case-insensitive, and ^ / $ match at line boundaries
let r = /^name: (\w+)$/.ignoresCase().anchorsMatchLineEndings()
print(text.matches(of: r).map(\.1))
// greedy vs reluctant
let html = "<b>bold</b> and <i>italic</i>"
print(html.firstMatch(of: /<.+>/)!.output)
print(html.firstMatch(of: /<.+?>/)!.output)
print(html.firstMatch(of: /<.+>/.repetitionBehavior(.reluctant))!.output)
Output:
["Alice", "bob", "Carol"]
<b>bold</b> and <i>italic</i>
<b>
<b>
Other options are dotMatchesNewlines(), asciiOnlyDigits(), asciiOnlyWordCharacters(), wordBoundaryKind(_:) and matchingSemantics(_:). You can also set them inside the pattern with the usual syntax, like /(?i)name/.
Unicode: matching Characters
By default a Swift regex matches Characters (extended grapheme clusters), just like String does. . matches one whole Character, even if it's made of several Unicode scalars, and canonically equivalent strings match the same pattern:
let word = "café" // é written as one scalar
let decomposed = "cafe\u{301}" // e + combining acute accent
print(word == decomposed)
print(decomposed.wholeMatch(of: /caf./) != nil) // . matches one Character
print(decomposed.wholeMatch(of: /cafe./) != nil)
print(decomposed.wholeMatch(of: /cafe./.matchingSemantics(.unicodeScalar)) != nil)
print(word.wholeMatch(of: /café/) != nil, decomposed.wholeMatch(of: /café/) != nil)
let flags = "Flags: 🇵🇱🇩🇪"
print(flags.matches(of: /\p{Regional_Indicator}+/).map(\.output))
print("👨👩👧 family".firstMatch(of: /\S/)!.output)
print("Zürich, Łódź".matches(of: /\p{L}+/).map(\.output))
Output:
true
true
false
true
true true
["🇵🇱🇩🇪"]
👨👩👧
["Zürich", "Łódź"]
With .matchingSemantics(.unicodeScalar) the regex works on scalars, which is how most other regex engines (including NSRegularExpression) behave.
Patterns known at run time: Regex(String)
When the pattern comes from user input or a config file, create the regex with try Regex(_:). The compiler can't know the captures, so the output type is AnyRegexOutput. You get captures by index or by name, and each one is optional:
import Foundation
// Runtime pattern: output type is AnyRegexOutput
let userPattern = #"(\w+)@(\w+)\.com"#
do {
let regex = try Regex(userPattern)
if let m = "mail bob@example.com now".firstMatch(of: regex) {
print(m.output.count)
print(m.output[1].substring ?? "nil", m.output[2].substring ?? "nil")
}
// Ask for a typed output; checked when the regex is created
let typed = try Regex(userPattern, as: (Substring, Substring, Substring).self)
if let m = "bob@example.com".wholeMatch(of: typed) {
print(m.1, m.2)
}
let named = try Regex(#"(?<key>\w+)=(?<value>\w+)"#)
if let m = "x=10".wholeMatch(of: named) {
print(m.output["key"]?.substring ?? "", m.output["value"]?.substring ?? "")
}
_ = try Regex("(unclosed")
} catch {
print("error:", error)
}
do {
_ = try Regex(#"(\w+)"#, as: (Substring, Substring, Substring).self)
} catch {
print("type error:", error)
}
Output:
3
bob example
bob example
x 10
error: expected ')'
type error: Cast to incorrect type 'Regex<(Substring, Substring, Substring)>', expected 'Regex<(Substring, Substring)>'
A raw string #"..."# saves you from doubling every backslash, as you have to in "\\d+".
RegexBuilder
Dense patterns are hard to read and hard to change. The RegexBuilder module (import RegexBuilder) lets you write the same pattern as a result builder. Here is /(\d{4})-(\d{2})-(\d{2})/ written with the builder:
import RegexBuilder
// Same as /(\d{4})-(\d{2})-(\d{2})/
let date = Regex {
Capture {
Repeat(.digit, count: 4)
}
"-"
Capture {
Repeat(.digit, count: 2)
}
"-"
Capture {
Repeat(.digit, count: 2)
}
}
if let m = "Released 2026-10-18".firstMatch(of: date) {
print(m.1, m.2, m.3)
print(type(of: m.output))
}
// Quantifiers and alternation
let price = Regex {
ChoiceOf {
"$"
"€"
"zł"
}
Optionally(.whitespace)
OneOrMore(.digit)
Optionally {
"."
Repeat(.digit, count: 2)
}
}
for s in ["$10", "€ 3.50", "zł99", "10$"] {
print(s, s.wholeMatch(of: price) != nil)
}
Output:
2026 10 18
(Substring, Substring, Substring, Substring)
$10 true
€ 3.50 true
zł99 true
10$ false
String literals in a builder match literally, so "." and "$" need no escaping. The main components are:
| Builder | Regex syntax |
|---|---|
OneOrMore(x) / ZeroOrMore(x) / Optionally(x) |
x+ / x* / x? |
Repeat(x, count: n), Repeat(x, 2...5) |
x{n}, x{2,5} |
ChoiceOf { a; b } |
a|b |
Capture { x } |
(x) |
.digit, .word, .whitespace, .any, .anyNonNewline |
\d, \w, \s, . with (?s), . |
CharacterClass("a"..."f"), .anyOf("xyz") |
[a-f], [xyz] |
Anchor.startOfLine, Anchor.wordBoundary |
^, \b |
Lookahead { x }, NegativeLookahead { x } |
(?=x), (?!x) |
Quantifiers take an optional behavior argument as well, for example OneOrMore(.any, .reluctant).
Converting a literal to a builder
Xcode can do this conversion for you. Right-click a regex literal and choose Refactor > Convert to Regex Builder, and it rewrites the literal as the equivalent Regex { ... } block. This is an Xcode refactoring. It is not available in the command-line tools on Windows or Linux.
You don't have to convert everything. Literals and builders compose: a literal (or any Regex) can be used as a component inside a builder, and its captures carry over.
import RegexBuilder
// Literals and builders compose both ways
let ident = /[A-Za-z_]\w*/
let call = Regex {
Capture { ident }
"("
Capture {
ZeroOrMore {
ident
Optionally(/,\s*/)
}
}
")"
}
if let m = "result = max(a, b, c)".firstMatch(of: call) {
print(m.1, "|", m.2)
}
// Character classes can be combined
let hexDigit = CharacterClass("a"..."f", "A"..."F", .digit)
let color = Regex {
"#"
Capture {
ChoiceOf {
Repeat(hexDigit, count: 6)
Repeat(hexDigit, count: 3)
}
}
Anchor.wordBoundary
}
print("#1E90FF #abc #12345 #xyz".matches(of: color).map(\.1))
let consonant = CharacterClass("a"..."z").subtracting(.anyOf("aeiou"))
print("strength".matches(of: Regex { OneOrMore(consonant) }).map(\.output))
// Lookahead: digits followed by "px", without consuming "px"
let px = Regex {
Capture { OneOrMore(.digit) }
Lookahead { "px" }
}
print("10px 2em 300px".matches(of: px).map(\.1))
Output:
max | a, b, c
["1E90FF", "abc"]
["str", "ngth"]
["10", "300"]
Since a builder is just Swift code, you can store pieces in constants (like ident and hexDigit), give them good names, and reuse them.
Capture transforms and TryCapture
Capture can take a transform closure that converts the matched Substring into another type, and the output type changes with it. TryCapture takes a transform that returns an optional. If it returns nil, that attempt fails and the engine backtracks, as if the pattern hadn't matched there:
import RegexBuilder
// Capture with a transform; TryCapture fails the match when the transform returns nil
enum Level: String { case debug, info, warn, error }
let entry = Regex {
Anchor.startOfLine
"["
TryCapture {
OneOrMore(.word)
} transform: { Level(rawValue: String($0).lowercased()) }
"] "
Capture {
OneOrMore(.digit)
} transform: { Int($0)! }
"ms "
Capture {
OneOrMore(.anyNonNewline)
}
}
.anchorsMatchLineEndings()
let log = """
[INFO] 12ms started
[TRACE] 1ms ignored, unknown level
[warn] 250ms slow query
[ERROR] 1300ms timeout
"""
for m in log.matches(of: entry) {
let (_, level, ms, message) = m.output
print(level, ms, message)
}
print(type(of: entry))
Output:
info 12 started
warn 250 slow query
error 1300 timeout
Regex<(Substring, Level, Int, Substring)>
The [TRACE] line was skipped because Level(rawValue: "trace") is nil. The output type (Substring, Level, Int, Substring) was inferred from the transforms, so ms is a real Int.
Reference: named captures in a builder
With many captures, positional access like m.5 gets confusing. Create a Reference of the capture's type, capture into it with Capture(as:), and read it back with match[reference]. A reference can also be used later in the same pattern as a backreference, which matches the same text again:
import RegexBuilder
// References name a capture so you can read it by key instead of position
let keyRef = Reference(Substring.self)
let valueRef = Reference(Int.self)
let setting = Regex {
Capture(as: keyRef) {
OneOrMore(.word)
}
ZeroOrMore(.whitespace)
"="
ZeroOrMore(.whitespace)
TryCapture(as: valueRef) {
OneOrMore(.digit)
} transform: { Int($0) }
}
if let m = "timeout = 30".wholeMatch(of: setting) {
print(m[keyRef], m[valueRef] * 2)
}
// A reference can also be matched again later (a backreference)
let quote = Reference(Substring.self)
let quoted = Regex {
Capture(as: quote) {
ChoiceOf { "\""; "'" }
}
Capture {
ZeroOrMore {
NegativeLookahead { quote }
CharacterClass.any
}
}
quote
}
for s in [#""double""#, "'single'", #""mixed'"#, #"'it"s'"#] {
print(s, s.wholeMatch(of: quoted).map { String($0.2) } ?? "no match")
}
Output:
timeout 60
"double" double
'single' single
"mixed' no match
'it"s' it"s
Foundation parsers as components
Foundation adds regex components that parse dates, numbers and currency values with its format styles. Their captures already have the parsed type:
import Foundation
import RegexBuilder
let line = "2026-10-18T09:30:00Z amount: 1,250.75 count: 42"
let regex = Regex {
Capture(.iso8601)
OneOrMore(.whitespace)
"amount: "
Capture(.localizedDouble(locale: Locale(identifier: "en_US")))
OneOrMore(.whitespace)
"count: "
Capture(.localizedInteger(locale: Locale(identifier: "en_US")))
}
if let m = line.wholeMatch(of: regex) {
let (_, date, amount, count) = m.output
print(type(of: m.output))
print(date.timeIntervalSince1970, amount * 2, count + 1)
}
Output:
(Substring, Date, Double, Int)
1792315800.0 2501.5 43
Other components include .date(format:locale:timeZone:), .localizedCurrency(code:locale:) and .localizedIntegerPercentage(locale:).
Regex and concurrency
Regex is not Sendable. In the Swift 6 language mode, a global let isoDate = /.../ in a library file fails to compile with "let 'isoDate' is not concurrency-safe because non-'Sendable' type 'Regex<...>' may have shared mutable state". (In main.swift, top-level variables are main-actor isolated instead, so you can't use them from other tasks.) One fix is to create the regex where it is used, for example with a computed global:
// Regex isn't Sendable, so it can't be a plain global constant in Swift 6 mode.
// A computed global builds a fresh value on each access instead.
var isoDate: Regex<(Substring, Substring, Substring, Substring)> {
/(\d{4})-(\d{2})-(\d{2})/
}
func years(in lines: [String]) async -> [Int] {
await withTaskGroup(of: Int?.self) { group in
for line in lines {
group.addTask {
let regex = isoDate // one Regex per task
return line.firstMatch(of: regex).flatMap { Int($0.1) }
}
}
var result: [Int] = []
for await y in group { if let y { result.append(y) } }
return result.sorted()
}
}
@main
struct Main {
static func main() async {
print(await years(in: ["from 2024-01-01", "none", "to 2026-12-31"]))
// Regex works on Substring too, so you can match inside a slice without copying
let text = "header: 2025-05-05 | body: 2026-06-06"
let body = text[text.firstRange(of: "body:")!.upperBound...]
print(body.firstMatch(of: isoDate)!.output.0)
}
}
Output (compiled with -parse-as-library):
[2024, 2026]
2026-06-06
A regex is compiled into its internal program on first use, and that program is cached in the Regex value. Inside one task or loop, create the regex once and reuse it. Don't rebuild it for every string you match.
Regex vs NSRegularExpression
Regex |
NSRegularExpression |
|
|---|---|---|
| Available since | Swift 5.7 (standard library) | Foundation |
| Pattern errors | compile time for literals | run time (try) |
| Captures | typed tuple, named labels, transforms | NSTextCheckingResult + NSRange |
| Unit of matching | Character (or scalars, opt-in) |
UTF-16 code unit |
| Ranges | Range<String.Index> |
NSRange |
| Replacement | closure with the typed match | $1 template strings |
| Builder DSL | RegexBuilder |
none |
New code should use Regex. NSRegularExpression is still useful in older code and for APIs that take an NSRange. The rest of this chapter covers it: NSRegularExpression in Swift, NSRegularExpression for mail validation and Replacing Substrings.
Summary
/pattern/creates aRegexthat the compiler checks. Captures become a typed tuple,(?<name>...)gives labeled elements, and optional groups giveSubstring?.#/.../#lets you write/without escaping it and allows multi-line patterns with whitespace and comments. In the Swift 5 mode, bare/.../needs theBareSlashRegexLiteralsfeature.wholeMatchchecks the whole string,firstMatchfinds the first match,prefixMatchmatches at the start, andmatches(of:)finds all matches.replacing,split,trimmingPrefix,containsandranges(of:)all accept a regex. Replacement closures get the typed match.- A regex can't be a
casepattern unless you define~=yourself. try Regex(string)builds a regex at run time with anAnyRegexOutputoutput. Useas:to get a typed one.RegexBuilderspells out patterns withCapture,TryCapture,Reference,OneOrMore,ChoiceOf,Repeatand character classes. It mixes freely with literals, and Xcode can convert a literal into a builder.Regexis notSendable. Create it where you use it, and reuse it within that scope.