iOS Regex Validation: Input Boundaries and Backtracking Risks

iOS Regex Validation: Input Boundaries and Backtracking Risks

iOS Regex Validation: Input Boundaries and Backtracking Risks

Even after iOS unit tests pass on a remote Mac, a form may still accept a trailing newline or full-width digits—or let an excessively long input tie up a thread. The problem is usually not the machine, but the validation contract: are you checking that the input contains a valid substring, or that the entire field is valid? The following approach uses a fixed-format business identifier to build repeatable acceptance checks, establishing correctness before investigating backtracking risks.

Define the field syntax as a contract

Suppose an identifier must consist of two uppercase ASCII letters, a hyphen, and six ASCII digits, such as AB-123456. Its total length is nine UTF-16 code units. Spaces, newlines, and implicit format conversions are not allowed.

Start by adding valid and invalid cases to the project's test target, then implement the validator. Do not use actual production user input as test data. Fixed fixtures are easier to reproduce and keep personal information out of test artifacts.

If the business rules allow trimming leading and trailing spaces, make that a separate step and test both the raw input and the trimmed result. A validation function should not silently modify its input; otherwise, the client, server, and audit records may end up with different identifiers.

Implement a true full match

Foundation uses UTF-16 for regular expression ranges, so you cannot create an NSRange directly from Swift's String.count. You can place the following implementation in an XCTest file, verify its behavior, and then move it into the application module:

import Foundation
import XCTest

private enum TicketCode {
    static let pattern = #"\A[A-Z]{2}-[0-9]{6}\z"#
    static let regex = try! NSRegularExpression(pattern: pattern)

    static func accepts(_ input: String) -> Bool {
        guard input.utf16.count == 9 else { return false }
        let full = NSRange(input.startIndex..<input.endIndex, in: input)
        guard let match = regex.firstMatch(
            in: input,
            options: [],
            range: full
        ) else {
            return false
        }
        return NSEqualRanges(match.range, full)
    }
}

final class TicketCodeTests: XCTestCase {
    func testValidationBoundaries() {
        let cases: [(String, Bool)] = [
            ("AB-123456", true),
            ("ab-123456", false),
            ("AB-12345", false),
            ("AB-1234567", false),
            ("AB-123456\n", false),
            (" AB-123456", false),
            ("AB-123456", false),
            ("AB-١٢٣٤٥٦", false),
            ("AB–123456", false),
            ("🙂AB-123456", false)
        ]
        for (input, expected) in cases {
            XCTAssertEqual(
                TicketCode.accepts(input),
                expected,
                "Unexpected result for \(input.debugDescription)"
            )
        }
    }
}

Here, try! is used only for a fixed, tested pattern defined in code. If the pattern comes from a file or configuration, use throwing initialization and report configuration failures. Compile the regular expression once rather than constructing a new object for every input.

\A and \z explicitly anchor the match to the beginning and end of the entire string. Keep the full-range comparison even if the pattern changes later, so validation does not degrade into a substring search.

Cover Unicode and length boundaries

If the field accepts only ASCII digits, use [0-9]. Do not treat \d as an equivalent: digit categories in Unicode regular expressions may include digits from other writing systems. A visually similar longer dash is not an ASCII hyphen either and should be explicitly rejected.

Length rules must also specify the unit. String.count counts extended grapheme clusters, UTF-16 length is used for Foundation ranges, and UTF-8 byte counts are suitable for transfer quotas. These three counts are not interchangeable. In particular, a general-purpose notes field should not inherit the nine-code-unit rule.

Add tests for empty strings, combining characters, carriage-return/line-feed sequences, and inputs just below and above the length limit. If the product requires Unicode normalization, first define the normalization form, then test acceptance before and after normalization. Do not loosen the identifier syntax merely to accommodate inputs that “look the same.”

The validator should reject raw input that does not meet the contract. Tolerant conversions belong in a separate layer with their own rules and tests.

Keep backtracking experiments out of ordinary tests

Do not challenge dangerous patterns with ever-growing inputs inside the normal XCTest process. Nested repetition such as (a+)+ may explore a large number of possible paths when a long string ends with a nonmatching character. A quick run on one short sample does not establish that a pattern is safe.

During code review, check first for nested quantifiers, overlapping alternatives, and unnecessary wildcards. When the field syntax permits a fixed length, prefer explicit character classes and repetition counts. For complex nested formats, consider a dedicated parser rather than adding more layers of regular expressions.

For complex patterns that must be retained, run fixed samples of increasing length in a separate command-line process. The parent process should enforce an overall deadline, terminate the child on timeout, and wait for it to exit. Start a separate process for each length, and record the pattern version, input length, exit status, and elapsed time—not the sensitive input itself.

Dispatching a task to a background queue and then stopping the wait for its result does not automatically cancel a match already in progress. The commonly used matching APIs in NSRegularExpression do not expose a directly configurable hard execution limit, and thread isolation is not resource isolation.

Create an acceptance record on the remote Mac

On a VPSPull cloud Mac, first record the output of sw_vers and xcodebuild -version, then run the test target containing the tests above. Retain the commit identifier, pattern text, and test results so you can distinguish code changes from changes in the system's regular expression implementation.

Run performance measurements separately with a fixed build configuration, rather than measuring while builds run in parallel. Set thresholds from repeated measurements in the same environment; do not treat a single wall-clock duration as a universal metric. After a system upgrade, rebuild the baseline before assessing regressions.

Finally, verify three things: valid input passes as a complete match; invalid input is rejected at clearly defined boundaries; and risk experiments cannot hold up the main test process. Also limit request or file sizes at the entry point, because computing a string's length itself requires scanning the input. Include these checks in merge acceptance criteria so regular expression changes are not approved on the strength of a few manual examples alone.

Frequently asked questions

Why check the range returned by firstMatch?

firstMatch may locate a valid substring inside an invalid field. Whole-field validation should require the returned range to equal the full input range and use explicit start and end boundaries.

Does an async timeout stop a regex match?

No. Stopping the wait does not interrupt an active NSRegularExpression match. Bound the input and simplify the pattern; investigate suspicious patterns in a separate process that can be terminated.

Validate your workflow on a dedicated Mac

Check the model, region, and rental term, then test it for a day. Live availability is shown in the console.