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
무엇을 정규식으로 사용해야합니까? –