NSDataDetector
を使用すると、文字列 に埋め込まれているリンクを見つけて、それらを置き換えることができます。例(インライン説明):
var string = "Hello http://google.com Google, hello http://www.apple.com Apple."
var nsString = string as NSString // NSString needed in order to work with NSRange
// Data detector for embedded links:
let detector = try! NSDataDetector(types: NSTextCheckingType.Link.rawValue)
let matches = detector.matchesInString(string, options: [],
range: NSRange(location: 0, length: nsString.length))
// Replace links, starting with the last one, otherwise ranges would change:
for match in matches.reverse() {
if let url = match.URL {
let replacement = "<href=\"\(url.absoluteString)\"></a>"
nsString = nsString.stringByReplacingCharactersInRange(match.range, withString: replacement)
}
}
string = nsString as String
print(string)
// Hello <href="http://google.com"></a> Google, hello <href="http://www.apple.com"></a> Apple.
正規表現を置き換えますか? – dasblinkenlight
正規表現にするべきことをアドバイスしてください。 –