find urls in a string using regex in swift

You can find URLs in a string using Regular Expressions in Swift by using NSRegularExpression class. Here's the code:

main.swift
func findURLs(in string: String) -> [URL] {
    var urls: [URL] = []
    let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
    detector?.enumerateMatches(in: string, options: [], range: NSMakeRange(0, string.utf16.count)) { (result, _, _) in
        guard let result = result,
              let url = result.url else { return }
        urls.append(url)
    }
    return urls
}
418 chars
11 lines

This function takes a string as input and returns an array of URLs found in the string. It uses NSDataDetector class to detect the URLs in the input string. The enumerateMatches(in:options:range:using:) method of NSDataDetector class is used to find the matches in the input string. The NSTextCheckingResult.CheckingType.link.rawValue option is used to detect URLs.

The result parameter in the closure contains information about the match found by the detector. We extract the URL from the result and append it to the array.

Here's an example of how to use the function:

main.swift
let string = "Check out this URL: https://www.google.com"
let urls = findURLs(in: string)
print(urls) // prints "[https://www.google.com]"
139 chars
4 lines

related categories

gistlibby LogSnag