Contents

url(scheme:user:password:host:port:path:query:fragment:)

Creates a regex component that matches a URL substring, capturing it as a Foundation URL.

Declaration

static func url(scheme: URL.ParseStrategy.ComponentParseStrategy<String> = .required, user: URL.ParseStrategy.ComponentParseStrategy<String> = .optional, password: URL.ParseStrategy.ComponentParseStrategy<String> = .optional, host: URL.ParseStrategy.ComponentParseStrategy<String> = .required, port: URL.ParseStrategy.ComponentParseStrategy<Int> = .optional, path: URL.ParseStrategy.ComponentParseStrategy<String> = .optional, query: URL.ParseStrategy.ComponentParseStrategy<String> = .optional, fragment: URL.ParseStrategy.ComponentParseStrategy<String> = .optional) -> Self

Parameters

Return Value

A RegexComponent that matches a URL.

Discussion

All the parameters to this method take a URL.ParseStrategy.ComponentParseStrategy value to configure the matching behavior for one component of the URL. The three possible values are:

The following example creates a Regex that matches a URL, when it contains a scheme and a host. It then matches against a source string that contains a date formatted in the en_US locale, some whitespace, and a valid URL. The regex defines a default value for the port with URL.ParseStrategy.ComponentParseStrategy.defaultValue(_:), and because the source URL doesn’t include a port, the captured URL adds it.

let source = "7/31/2022, 5:15:12 AM  https://www.example.com/productList?query=slushie"
let matcher = Regex {
    One(.dateTime(date: .numeric,
                  time: .standard,
                  locale: Locale(identifier: "en_US"),
                  timeZone: TimeZone(identifier: "PST")!))
    OneOrMore(.horizontalWhitespace)
    Capture {
        One(.url(scheme: .required,
                 user: .optional,
                 password: .optional,
                 host: .required,
                 port: .defaultValue(8088),
                 path: .optional,
                 query: .optional,
                 fragment: .optional))
    }
}
guard let match = source.firstMatch(of: matcher) else { return }
let url = match.1 // url = https://www.example.com:8088/productList?query=slushie