gpt4 book ai didi

swift - 从字符串中获取子字符串

转载 作者:搜寻专家 更新时间:2023-11-01 06:59:34 24 4
gpt4 key购买 nike

我有来自服务器的以下字符串:

I agree with the <a>((http://example.com)) Terms of Use</a> and I've read the <a>((http://example2.com)) Privacy</a>

现在我想在标签中这样显示它:

I agree with the <a href="http://google.com">Terms of Use</a> and I've read the <a href="http://google.com">Privacy</a>

我试图从字符串中删除 (( http://example.com )) 并将其保存在另一个字符串中。我需要链接,因为稍后应该可以点击文本。

我试过这个来获取我想要的文本:

//the link:
let firstString = "(("
let secondString = "))"

let link = (text.range(of: firstString)?.upperBound).flatMap { substringFrom in
(text.range(of: secondString, range: substringFrom..<text.endIndex)?.lowerBound).map { substringTo in
String(text[substringFrom..<substringTo])
}
}

//the new text
if let link = link {
newString = text.replacingOccurrences(of: link, with: kEmptyString)
}

我从这里得到这个:Swift Get string between 2 strings in a string

问题是它只删除了 (( )) 括号内的文本。括号还在。我尝试使用索引的偏移量,但这并没有改变任何东西。此外,如果文本中只有一个链接,此解决方案也适用。如果有多个链接,我认为它们应该被存储并且我必须循环遍历文本。但我不知道该怎么做。我尝试了很多东西,但我没有得到这个工作。是否有更简单的方法来完成我想做的事情?

最佳答案

您可以使用正则表达式进行快速搜索替换。

let text = "I agree with the <a>((http://example.com)) Terms of Use</a> and I've read the <a>((http://example2.com)) Privacy</a>"
let resultStr = text.replacingOccurrences(of: "<a>\\(\\(([^)]*)\\)\\) ", with: "<a href=\"$1\">", options: .regularExpression, range: nil)
print(resultStr)

输出:

I agree with the <a href="http://example.com">Terms of Use</a> and I've read the <a href="http://example2.com">Privacy</a>

关于swift - 从字符串中获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51481260/

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