2016-05-11 3 views
2

SwiftのRegexを使用してHTML文字列を文字列で置き換えようとしています。基本的に「1,2,3」のような数字が「Appendices」という単語や世界の「Appendix」の前にある1つの数字の前にある場合はいつでも、ハイパーリンクタグを作成したいと思います。RegexはSwiftのhtml文字列を置き換えます

例えば

私は、文字列があります。

See Appendices 1 , 9 and 27. You should also see the Appendices 28, 45 and 37. Also see Appendix 19. See also chapter 19 and Verses 38 and 45 

をそして私はそれを交換したいと思います:

See Appendices <a href="Appendix://1"/>1</a> , <a href="Appendix://9"/>9</a> and <a href="Appendix://27"/>27</a> . You should also see the Appendices <a href="Appendix://28"/>28</a> , <a href="Appendix://45"/>45</a> and <a href="Appendix://37"/>37</a> . Also see <a href="Appendix://19"/>Appendix 19</a> . See also chapter 19 and Verses 38 and 45 
+1

http://www.regexr.com/のようなツールを使って正規表現をテストするべきでしょう。 –

答えて

0

私はこれを行う方法書いてしまった:

func findAndReplaceAppendixDeeplinks(theText:String)->String{ 


    var text = theText 

    var innerRangeIncrement:Int = 0 

    do { 
     let regex = try? NSRegularExpression(pattern: "(Appendix|Appendices|App.) (\\d+)((, |and|&)?()?(\\d+)?)+", options: NSRegularExpressionOptions.CaseInsensitive) 

     let range = NSMakeRange(0, text.characters.count) 

     let matches = regex!.matchesInString(text, options: NSMatchingOptions.WithoutAnchoringBounds, range: range) 

     innerRangeIncrement = 0 

     for match in matches { 

      let theMatch:String = (text as NSString).substringWithRange(match.range) 

      print("the new match is \(theMatch)") 



      do { 
       let regex1 = try? NSRegularExpression(pattern: "(\\d+)", options: NSRegularExpressionOptions.CaseInsensitive) 


       let innerMatches = regex1!.matchesInString(theText, options: NSMatchingOptions.WithoutAnchoringBounds, range: match.range) 



       for innerMatch in innerMatches{ 


        let innerString:String = (theText as NSString).substringWithRange(innerMatch.range) 

        print("innerString is \(innerString)") 


        let replacementString = "<a href=\"Appendix://\(innerString)\">\(innerString)</a>" 

        printIfDebug("replacementString is \(replacementString)") 


        let innerRange = NSRange(location: innerMatch.range.location + innerRangeIncrement , length: innerMatch.range.length) 

        print("now looking for character position \(innerMatch.range.location + innerRangeIncrement)") 

        text = regex1!.stringByReplacingMatchesInString(text, options: NSMatchingOptions.WithoutAnchoringBounds, range: innerRange, withTemplate: replacementString) 

        innerRangeIncrement = innerRangeIncrement + replacementString.length - innerString.length 
        printIfDebug("inner increment value is \(innerRangeIncrement)") 
        printIfDebug(text) 



       } 


       printIfDebug("outer increment value is \(innerRangeIncrement)") 

      } 
     } 

    } 

    return text 
} 
関連する問題