从字符串中获取子字符串

时间:2018-07-23 14:30:06

标签: swift string hyperlink range

我从服务器获取以下字符串:

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))并将其保存在另一个String中。我需要链接,因为文本以后可以单击。

我试图这样做以获得我想要的文本:

//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

此问题是仅删除(())括号内的文本。括号仍然在那里。我尝试使用索引的偏移量,但这没有任何改变。此外,如果文本中只有一个链接,则此解决方案有效。如果有多个链接,我认为应该将它们存储起来,并且必须遍历文本。但是我不知道该怎么做。我尝试了很多事情,但没有成功。也许有一种更简单的方法来获得我想要的东西?

2 个答案:

答案 0 :(得分:2)

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

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)

输出:

  

我同意使用条款,并且已经阅读了隐私保护< / a>

答案 1 :(得分:0)

您可以使用类似的方法来获取链接:

let s = "I agree with the ((http://example.com)) Terms of Use and I've read the ((http://example2.com)) Privacy"

let firstDiv = s.split(separator: "(") // ["I agree with the ", "http://example.com)) Terms of Use and I\'ve read the ", "http://example2.com)) Privacy"]
let mid = firstDiv[1] // http://example.com)) Terms of Use and I've read the
let link1 = mid.split(separator: ")")[0] // http://example.com
let link2 = firstDiv[2].split(separator: ")")[0] // http://example2.com