How to Extract Regex Matches in Swift Without NSRange Errors

Written by

in

Quick answer: In Swift 5.7 and later, use text.matches(of: try Regex(pattern)).map { String(text[$0.range]) } to extract matches without touching NSRange. If you need to support older OS versions or NSRegularExpression, create the input range with NSRange(text.startIndex..., in: text) and convert each NSTextCheckingResult.range back using Range($0.range, in: text).

Why this happens

When you use NSRegularExpression in Swift, matches(in:options:range:) returns an array of NSTextCheckingResult objects. Each result exposes a range property of type NSRange, which measures offsets in UTF-16 code units because NSRegularExpression operates on NSString internally.

Swift’s String, however, uses Range<String.Index> to slice substrings safely across extended grapheme clusters such as emojis and accented characters. Passing text.count to NSMakeRange(0, ...) or trying to slice a Swift String directly with an NSRange either fails to compile or produces out-of-bounds crashes when the text contains multi-byte characters like flags (πŸ‡©πŸ‡ͺ) or currency symbols.

How to fix it

1. Use Swift’s native Regex and matches(of:) (Swift 5.7+)

If your app targets iOS 16, macOS 13, or newer, you can avoid NSRegularExpression and NSRange completely. Swift’s native Regex type works directly with String.Index, so matches(of:) returns ranges you can subscript straight onto the original string.

For a dynamic pattern stored in a String, initialize Regex inside a do/catch block:

func matches(for pattern: String, in text: String) -> [String] {
    do {
        let regex = try Regex(pattern)
        return text.matches(of: regex).map { String(text[$0.range]) }
    } catch {
        print("Invalid regex: \(error.localizedDescription)")
        return []
    }
}

let sample = "πŸ‡©πŸ‡ͺ€4€9"
let matched = matches(for: "[0-9]", in: sample)
print(matched) // ["4", "9"]

If your pattern is known at compile time, you can pass a regex literal directly to matches(of:) without any error handling:

let sample = "πŸ‡©πŸ‡ͺ€4€9"
let digits = sample.matches(of: /[0-9]/).map { String(sample[$0.range]) }
print(digits) // ["4", "9"]

2. Convert between NSRange and Range with NSRegularExpression

If you must support older OS versions or already rely on NSRegularExpression, use Swift’s built-in NSRange(_:in:) and Range(_:in:) initializers. These handle UTF-16 length calculations automatically, so emojis and special characters will not break your indices.

import Foundation

func matches(for pattern: String, in text: String) -> [String] {
    do {
        let regex = try NSRegularExpression(pattern: pattern)
        let nsRange = NSRange(text.startIndex..., in: text)
        let results = regex.matches(in: text, range: nsRange)
        return results.compactMap {
            Range($0.range, in: text).map { String(text[$0]) }
        }
    } catch {
        print("Invalid regex: \(error.localizedDescription)")
        return []
    }
}

let sample = "πŸ‡©πŸ‡ͺ€4€9"
let matched = matches(for: "[0-9]", in: sample)
print(matched) // ["4", "9"]

Using compactMap with Range($0.range, in: text) safely unwraps each converted range instead of force-unwrapping with !. While Range($0.range, in: text)! is generally safe when text has not been mutated, compactMap eliminates any risk of a runtime crash.

3. Extract capture groups with a String extension

If you need both the full match and individual capture groups, NSTextCheckingResult stores every group in range(at:), where index 0 is the entire match and 1... are the captured substrings. An optional capture group that did not match returns NSNotFound for its location.

You can wrap this logic in a String extension that returns [[String]], substituting an empty string for unmatched optional groups:

import Foundation

extension String {
    func matchingStrings(regex pattern: String) -> [[String]] {
        guard let regex = try? NSRegularExpression(pattern: pattern) else {
            return []
        }
        let nsRange = NSRange(startIndex..., in: self)
        let results = regex.matches(in: self, range: nsRange)
        return results.map { result in
            (0..<result.numberOfRanges).map { index in
                let rangeBounds = result.range(at: index)
                guard rangeBounds.location != NSNotFound,
                      let range = Range(rangeBounds, in: self) else {
                    return ""
                }
                return String(self[range])
            }
        }
    }
}

let pairs = "prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")
// [["fix12", "1", "2"], ["fix45", "4", "5"]]

let optionalPrefix = "12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// [["12", "12"]]

This approach gives you a predictable two-dimensional array: each inner array holds the full match at index 0, followed by each capture group in order.

How to prevent it

  • Prefer Regex on modern targets: Use Swift’s native Regex and matches(of:) whenever your deployment target is iOS 16 / macOS 13 or later.
  • Never pass text.count to NSRange: String.count counts grapheme clusters, not UTF-16 code units. Always use NSRange(text.startIndex..., in: text) when working with NSRegularExpression.
  • Check for NSNotFound on capture groups: When reading result.range(at: index), verify location != NSNotFound before converting to Range<String.Index> so optional groups do not fail.
  • Test with multi-byte Unicode: Include strings containing emojis, flags, or accented characters in your unit tests to catch NSString length mismatches early.

FAQ

Why does my NSRegularExpression fail on strings with emojis?

NSRegularExpression counts UTF-16 code units, while Swift’s text.count counts user-perceived characters. A flag emoji like πŸ‡©πŸ‡ͺ has a count of 1 in Swift but a UTF-16 length of 4, so using text.count truncates the search range and misses matches at the end of the string.

Is force-unwrapping Range($0.range, in: text)! safe?

It is safe as long as text is the exact, unmodified String you passed to matches(in:range:) and you are reading $0.range (the full match). For capture groups via range(at:), use optional binding instead because unmatched optional groups return NSNotFound.

Should I use Regex or NSRegularExpression in new Swift projects?

Use Swift’s native Regex (try Regex(pattern) or /pattern/ literals) if your app targets iOS 16, macOS 13, or later. It is type-safe, faster to write, and eliminates NSRange conversions altogether.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.