gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:29 24 4
gpt4 key购买 nike

我正在尝试在 Swift 中使用 Regex 将 HTML 字符串替换为字符串。基本上只要有一组数字(例如“1、2 和 3”)前面有单词“Appendices”或单个数字(例如 1)前面有世界“Appendix”,我想为其创建超链接标签。

例如我有一个字符串:

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

最佳答案

我最终写了一个方法来做到这一点:

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
}

关于ios - 正则表达式替换 Swift 中的 html 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37172383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com