Lesson 92 of 146 ยท Standard Library and Foundation
Regular Expressions
Learn Swift regular expressions - regex literals, matches, captures with typed output, named groups, replacing, runtime Regex(String), and the readable RegexBuilder DSL, with real compiler errors.
A regular expression (regex) is a compact pattern that describes a set of strings: "three digits, a dash, then four digits", or "a word followed by an optional s". Regexes are how programs validate input, pull numbers out of log lines, and rewrite text in bulk. Since Swift 5.7 regex is part of the language itself. You can write a pattern as a literal, the compiler checks it, and the captured pieces come back as typed values rather than a bag of strings.
Swift offers two ways to write the same pattern. A regex literal such as /\d+/ uses the classic compact syntax you may know from other languages. RegexBuilder lets you assemble a pattern from readable Swift code. This lesson teaches both, the matching functions you call on strings, and the mistakes people make. It assumes you have read Text Processing. You do not need to import Foundation for any of it: regex lives in the standard library (and RegexBuilder is a separate module you import).
Your first regex literal
Put a pattern between slashes. The simplest question is "does this string contain a match?", answered with firstMatch(of:), which returns nil when nothing matches.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.
The first number is 4821, found at offset 6. \d+ means "one or more digits": \d is any digit, and + repeats it. The search for refund finds nothing, so firstMatch is nil and the comparison prints true. Note that contains(_:) also accepts a regex, which is the shortest form of a yes/no check.
match.output is the matched text, a Substring. The match also remembers range, the String.Index range where it was found.
Whole matches, prefixes, and all matches
Different jobs need different match functions:
| Function | Question it answers |
|---|---|
firstMatch(of:) |
Find the first match anywhere in the string |
wholeMatch(of:) |
Does the entire string match the pattern? |
prefixMatch(of:) |
Does the string start with a match? |
matches(of:) |
Give me all the matches, as an array |
Validation almost always wants wholeMatch. Using firstMatch for validation is the classic bug: the pattern /\d{4}/ finds four digits inside "abc12345xyz" and "validates" garbage.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.
The four checks print true, false, true, true. Only the first one is a real validation; means "exactly five times". The second to last test shows why firstMatch is not validation. The second part collects ["1", "22", "333"] and sums them to 356.
Common pattern pieces
You will use a small vocabulary again and again:
\da digit,\wa word character (letter, digit, underscore),\swhitespace;.any character except a newline.[abc]one of a, b or c;[a-z]a range;[^0-9]anything that is not a digit.*zero or more,+one or more,?optional,exactly n,{n,m}between n and m.^start of the string,$end of the string,\ba word boundary.a|beither a or b;( )groups and captures.
Quantifiers are greedy: they grab as much as they can. Add ? to make one lazy, so /<.+?>/ matches the shortest tag-like piece, not everything between the first < and the last >.
Captures: pulling out parts
Parentheses mark parts of the match you want back. Here is the part of Swift's regex that other languages do not have: the output type reflects the pattern. A match with captures gives you a tuple, and each capture has its type known at compile time.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.
match.output is a tuple (Substring, Substring, Substring, Substring): the whole match first, then one element per capture group. It prints 2025-03-14, then 2025 03 14, then 2026. In the second loop, (?:...) is a non-capturing group (it groups without capturing), and the optional capture (\d+) inside it becomes Substring?. So v2 prints 2 none and v2.5 prints 2 5.
Numbered captures are fragile: add a group at the front and everything shifts. Named captures fix that, and Swift turns the names into properties.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.
You read match.level, match.date and match.text directly, and the compiler knows they exist. Misspell one, say match.levle, and you get a normal compile error instead of a runtime surprise.
Converting while you capture
Regex can convert the captured text as part of matching with TryCapture, which you will meet in the RegexBuilder section. With literals you convert yourself, for example with Int(year). The result is an optional because a pattern like \d+ can match a number too large for Int.
Replacing text
replacing(_:with:) takes a regex and either a fixed string or a closure that builds the replacement from each match. replace(_:with:) does the same in place on a var.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.
You see call [phone] or [phone] today, then price 10, then 24, then 03/14/2025, then [ too many spaces ]. The closure form is where typed output shines: m.1, m.2, m.3 are the three captured Substrings.
Options and flags
Regex options change how matching works. Common ones are ignoresCase(), anchorsMatchLineEndings() (so ^ and $ match at each line, not only at the string's ends), and dotMatchesNewlines(). You chain them on the regex value.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.
Counts: 1, then 3; ^ without the option sees only the very start of the string, so one match, and with anchorsMatchLineEndings() it finds ["roses", "violets"].
When the pattern is wrong
A regex literal is checked at compile time. A typo is not a runtime crash, it is an error you see before the program runs.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.
The compiler stops with:
main.swift:1:19: error: cannot parse regular expression: expected ')'
``` Fix it by balancing the parentheses: `/(\d+)/`.
Sometimes the pattern is only known at run time: it comes from a settings file or a user's search box. Then you build a `Regex` from a `String` with `try`. The output type is no longer known, so it becomes `AnyRegexOutput`.
<!--tryit:7-->
The first call returns `3`. The second returns `-1` because `Regex("(unclosed")` throws, and `try?` turns the failure into `nil`. The `do/catch` shows the error for an invalid range: `error: character 'z' must compare less than or equal to 'a'`. The last block shows how to read captures from an `AnyRegexOutput`: index into it and ask for `.substring`.
Notice the **raw string** `#"..."#`. In a normal string you would have to double every backslash (`"\\d+"`). With one `#` on each side, backslashes are plain characters. Regex literals do not need this. If your pattern contains slashes, use an extended literal with `#/.../#`, e.g. `#/https?://\S+/#`.
## RegexBuilder: readable patterns
Long regexes become unreadable ("regex write-only syndrome"). `RegexBuilder` expresses the same ideas as Swift code, with names, comments and reuse. You import it and build a `Regex { ... }` from components.
<!--tryit:8-->
`Capture { ... }` marks the part you want, `Repeat(..., count:)` says how many times, and a string literal inside the builder matches itself exactly. The program prints `2025-03-14 2025 03 14`. Reading it is easier than `/(\d{4})-(\d{2})-(\d{2})/` once patterns grow.
The real power is **conversion while matching**. `TryCapture` takes a transform and the match fails if the transform returns `nil`. Combine it with a `Reference` to read a capture by name.
<!--tryit:9-->
The first capture is an `Int`, not a `Substring`: `let (_, quantity, unit, name) = match.output` gives you `quantity: Int`. The broken line `x kg broken` does not start with digits, so `wholeMatch` returns `nil` and the loop prints `skipped: x kg broken`. After it, you get the three parsed items: `3 kg rice`, `250 g flour`, `12 l milk`. `ChoiceOf` is the builder form of `kg|g|l`. Alternatives are tried in order, so when one is a prefix of another and you use `firstMatch`, list the longer one first.
When to use which? Use a **literal** for short patterns that you and your team read easily. Switch to **RegexBuilder** when the pattern has several parts, needs conversions (`TryCapture`), or must be maintained by others. You can also embed a literal inside a builder.
## Pitfalls and good habits
- **Validate with `wholeMatch`**, not `firstMatch`, or anchor with `^...$`.
- **Greedy versus lazy.** `.+` swallows as much as it can; `.+?` as little as it can.
- **Do not parse HTML or nested structures with regex.** Patterns cannot count nesting. Use a real parser (for JSON see [Working with JSON](/swift/json)).
- **Catastrophic backtracking.** Nested quantifiers such as `(a+)+b` can take exponential time on certain inputs. Never run an untrusted pattern or an untrusted input through a complicated expression without limits.
- **Characters, not bytes.** Swift regexes match on `Character`s by default, so `.` matches an emoji as one unit.
- **Simple jobs deserve simple tools.** If `split`, `hasPrefix` or `contains("text")` solves it, use that; it is easier to read.
## Check your understanding
<!--quiz:0-->
## Summary
- A regex literal `/pattern/` is checked by the compiler and produces a typed `Regex`; `Regex(String)` builds one at run time and can throw.
- `firstMatch`, `wholeMatch`, `prefixMatch` and `matches(of:)` answer different questions; use `wholeMatch` to validate.
- Captures return a tuple (`match.output`) with the whole match first; optional groups give optionals; named groups `(?<name>...)` become properties.
- `replacing(_:with:)` accepts a string or a closure over the match; `replace` edits a variable in place.
- Options such as `ignoresCase()` and `anchorsMatchLineEndings()` are chained onto the regex.
- Use raw strings `#"..."#` and extended literals `#/.../#` to avoid doubling backslashes.
- `RegexBuilder` (`Capture`, `TryCapture`, `ChoiceOf`, `Repeat`, `OneOrMore`) writes patterns as readable Swift and can convert captures to real types.
- Do not parse nested formats with regex, and beware of nested quantifiers.
Next: [Dates and Times](/swift/foundation-dates) covers `Date`, `Calendar`, formatting and time zones.
Track your progress
Create a free account to tick off lessons and pick up where you left off on any device.
of Swift lessons completed