Structure_StringProcessing5.9.0

    Regex

    A regular expression.

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

    Regular expressions are a concise way of describing a pattern, which can help you match or extract portions of a string. You can create a Regex instance using regular expression syntax, either in a regex literal or a string.

    // 'keyAndValue' is created using a regex literal
    let keyAndValue = /(.+?): (.+)/
    // 'simpleDigits' is created from a pattern in a string
    let simpleDigits = try Regex("[0-9]+")

    You can use a Regex to search for a pattern in a string or substring. Call contains(_:) to check for the presence of a pattern, or firstMatch(of:) or matches(of:) to find matches.

    let setting = "color: 161 103 230"
    if setting.contains(simpleDigits) {
        print("'\(setting)' contains some digits.")
    }
    // Prints "'color: 161 103 230' contains some digits."

    When you find a match, the resulting Match type includes an Match.output property that contains the matched substring along with any captures:

    if let match = setting.firstMatch(of: keyAndValue) {
        print("Key: \(match.1)")
        print("Value: \(match.2)")
    }
    // Key: color
    // Value: 161 103 230

    When you import the RegexBuilder module, you can also create Regex instances using a clear and flexible declarative syntax. Using this style, you can combine, capture, and transform regexes, RegexBuilder types, and custom parsers.

    Citizens in _StringProcessing

    Conformances

    Members

    Citizens in _StringProcessing

    where Output == AnyRegexOutput

    Members

    Available in RegexBuilder

    Members