2016-02-22 78 views
2

我們的應用程序API返回的自定義格式的字段用戶提到只是想: 「這是爲提@文本(史蒂夫| USER_ID)。 因此,在顯示它之前UITextView,需要處理文本,找到該模式,並取而代之的是更友好的用戶界面。 最終結果將爲「這是一個提及@steve的文本」其中@steve應具有鏈接屬性,其中user_id爲。基本上與Facebook相同的功能。替換正則表達式匹配屬性串和文本

首先,我創建了一個UITextView擴展,併爲正則表達式模式提供了一個匹配函數。

extension UITextView { 
    func processText(pattern: String) { 
     let inString = self.text 
     let regex = try? NSRegularExpression(pattern: pattern, options: []) 
     let range = NSMakeRange(0, inString.characters.count) 
     let matches = (regex?.matchesInString(inString, options: [], range: range))! as [NSTextCheckingResult] 

     let attrString = NSMutableAttributedString(string: inString, attributes:attrs) 

     //Iterate over regex matches 
     for match in matches { 
      //Properly print match range 
      print(match.range) 

      //A basic idea to add a link attribute on regex match range 
      attrString.addAttribute(NSLinkAttributeName, value: "\(schemeMap["@"]):\(must_be_user_id)", range: match.range) 

      //Still text it's in format @(steve|user_id) how could replace it by @steve keeping the link attribute ? 
     } 
    } 
} 

//To use it 
let regex = ""\\@\\(([\\w\\s?]*)\\|([a-zA-Z0-9]{24})\\)"" 
myTextView.processText(regex) 

這就是我現在所擁有的,但我stucked試圖讓最終的結果

非常感謝!

回答

4

我改變了你的正則表達式,但得到了一個不錯的結果。稍微修改了一下代碼,所以你可以在Playgrounds中直接測試它。

func processText() -> NSAttributedString { 
    let pattern = "(@\\(([^|]*)([^@]*)\\))" 
    let inString = "this is a text with mention for @(steve|user_id1) and @(alan|user_id2)." 
    let regex = try? NSRegularExpression(pattern: pattern, options: []) 
    let range = NSMakeRange(0, inString.characters.count) 
    let matches = (regex?.matchesInString(inString, options: [], range: range))! 

    let attrString = NSMutableAttributedString(string: inString, attributes:nil) 
    print(matches.count) 
    //Iterate over regex matches 
    for match in matches.reverse() { 
     //Properly print match range 
     print(match.range) 

     //Get username and userid 
     let userName = attrString.attributedSubstringFromRange(match.rangeAtIndex(2)).string 
     let userId = attrString.attributedSubstringFromRange(match.rangeAtIndex(3)).string 

     //A basic idea to add a link attribute on regex match range 
     attrString.addAttribute(NSLinkAttributeName, value: "\(userId)", range: match.rangeAtIndex(1)) 

     //Still text it's in format @(steve|user_id) how could replace it by @steve keeping the link attribute ? 
     attrString.replaceCharactersInRange(match.rangeAtIndex(1), withString: "@\(userName)") 
    } 
    return attrString 
} 
+0

搭檔,但有一個問題,如果您有2個用戶,只需將NSLinkAttributeName應用到最後一個! – Steve

+0

對不起,沒有考慮到它。請檢查我的更新解決方案。 –

+0

非常感謝,作品像魅力! – Steve

相關問題