You can find URLs in a string using Regular Expressions in Swift by using NSRegularExpression
class. Here's the code:
main.swift418 chars11 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.swift139 chars4 lines
gistlibby LogSnag