Swift extract regex matches
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Extracting regex matches in Swift usually means two separate tasks: finding the text that matches a pattern and converting Foundation ranges back into native Swift string ranges safely. The mechanics are straightforward once you know where the friction comes from. Most problems come from NSRange versus String.Index, not from the regex pattern itself.
Use NSRegularExpression for broad compatibility
NSRegularExpression is still the most compatible choice across existing Swift codebases. You compile the pattern once, run it against a string, and convert each NSTextCheckingResult range back into a Swift range before slicing the string.
The key step is Range(match.range, in: text). You should not try to use NSRange offsets directly on Swift strings, because Swift strings are Unicode-correct and are not indexed by simple integer positions.
Extract capture groups, not just whole matches
Real regex work often needs submatches. For example, if you want both the count and the fruit name from a sentence, capture groups are the right tool.
Group 0 is always the whole match. Capturing groups begin at index 1, which is why range(at: 1) and range(at: 2) extract the subparts.
Reuse compiled regex objects
If you run the same pattern repeatedly, compile it once and reuse it. That keeps the hot path cleaner and avoids repeating the pattern-validation cost.
Using try! here is reasonable because the pattern is a hard-coded programmer constant. If the pattern is dynamic or user-supplied, keep the do and catch flow instead.
Newer Swift regex syntax exists, but compatibility matters
Newer Swift versions also have native regex features, which can feel more Swifty than NSRegularExpression. That is a good option in modern projects, but NSRegularExpression is still the safest baseline when you are writing code that must fit older app targets or mixed UIKit and Foundation-heavy code.
So if you are answering "how do I extract regex matches in Swift?" for the broadest audience, Foundation remains the most portable answer.
Common Pitfalls
The most common mistake is trying to slice a Swift string directly with NSRange integers. Always convert through Range(..., in: text) first.
Another issue is forgetting that capture group 0 is the full match. If you want the first parenthesized part, use range(at: 1).
Developers also recreate the regex for every call even when the pattern never changes. Compiling once is usually simpler and faster.
Finally, remember that regex patterns live inside Swift string literals, so escaping rules matter. Raw string syntax such as #"...pattern..."# often makes patterns much easier to read.
Summary
- In Swift,
NSRegularExpressionis the most compatible way to extract regex matches. - Convert every
NSRangeback to a SwiftRangebefore slicing the string. - Use capture groups with
range(at:)when you need structured submatches. - Reuse compiled regex objects when the same pattern is used repeatedly.
- Raw string literals make regex patterns easier to write and maintain.

