StructureRegexBuilder5.9.0

    Capture

    A regex component that saves the matched substring, or a transformed result, for access in a regex match.

    iOS
    16.0+
    macOS
    13.0+
    tvOS
    16.0+
    watchOS
    9.0+
    struct Capture<Output>

    Use a Capture component to capture one part of a regex to access separately after matching. In the example below, regex matches a dollar sign ("$") followed by one or more digits, a period ("."), and then two additional digits, as long as that pattern appears at the end of the line. Because the Capture block wraps the digits and period, that part of the match is captured separately.

    let transactions = """
        CREDIT     109912311421    Payroll   $69.73
        CREDIT     105912031123    Travel   $121.54
        DEBIT      107733291022    Refund    $8.42
        """
    
    let regex = Regex {
        "$"
        Capture {
          OneOrMore(.digit)
          "."
          Repeat(.digit, count: 2)
        }
        Anchor.endOfLine
    }
    
    // The type of each match's output is `(Substring, Substring)`.
    for match in transactions.matches(of: regex) {
        print("Transaction amount: \(match.1)")
    }
    // Prints "Transaction amount: 69.73"
    // Prints "Transaction amount: 121.54"
    // Prints "Transaction amount: 8.42"

    Each Capture block increases the number of components in the regex’s output type. In the example above, the capture type of each match is (Substring, Substring).

    By providing a transform function to the Capture block, you can change the type of the captured value from Substring to the result of the transform. This example declares doubleValueRegex, which converts the captured amount to a Double:

    let doubleValueRegex = Regex {
        "$"
        Capture {
            OneOrMore(.digit)
            "."
            Repeat(.digit, count: 2)
        } transform: { Double($0)! }
        Anchor.endOfLine
    }
    
    // The type of each match's output is `(Substring, Double)`.
    for match in transactions.matches(of: doubleValueRegex) {
        if match.1 >= 100.0 {
            print("Large amount: \(match.1)")
        }
    }
    // Prints "Large amount: 121.54"

    Throwing an error from a transform closure aborts matching and propagates the error out to the caller. If you instead want to use a failable transformation, where a nil result participates in matching, use TryCapture instead of Capture.

    Citizens in RegexBuilder

    Conformances

    Members