2016-09-09 4 views
-3

String에서 하위 문자열 끝 부분에 문자를 추가해야하는 프로젝트에서 작업하고 있습니다. 예iOS의 String에서 SubString의 시작과 끝 부분에 문자 추가 Swift

Given String 
"Hello http://google.com Google." 
Result should be 
"Hello <a href="">http://www.google.com</a> The site for google." 

나는 그것이 동적으로 문자열의 위치에 대한 확실하지 않습니다. 상담하십시오.

+2

정규식을 바꾸시겠습니까? – dasblinkenlight

+0

무엇을 정규식으로 사용해야합니까? –

답변

2

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. 
관련 문제