正则表达式替换Swift中的html字符串

时间:2016-05-11 20:10:42

标签: ios regex swift

我试图在Swift中使用Regex用字符串替换HTML字符串。基本上任何时候都有一组数字,比如“1,2和3”,前面加上“附录”一词,或者一个数字,例如1号,前面是世界'附录',我想为它创建超链接标签。

例如我有一个字符串:

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 个答案:

答案 0 :(得分: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
}