【问题标题】:How two get a substring that is in between two blocks of text in another string in Swift 2.0两个如何在 Swift 2.0 中获取另一个字符串中两个文本块之间的子字符串
【发布时间】:2015-11-20 11:13:15
【问题描述】:

我有一个这样的字符串:

    let str = "<mylabel>Here is a label</mylabel>"

如何获得带有文本“Here is a label”的子字符串?有什么花哨的方法可以做到这一点,还是我必须使用 componentsSeparatedByString? 非常感谢

【问题讨论】:

标签: xcode string swift swift2


【解决方案1】:

您可以使用NSAttributedString(HTML:, documentAttributes:) 提取简单的 HTML 实体:

let str = "<mylabel>Here is a label</mylabel>"
if let html = str.dataUsingEncoding(NSUTF8StringEncoding), let result = NSAttributedString(HTML: html, documentAttributes: nil) {
    print(result.string)  // "Here is a label"
}

对于更复杂的工作,最好使用NSXMLParser或第三方库。

【讨论】:

    【解决方案2】:

    这解决了问题:

    let str = "<mylabel>Here is a label</mylabel>"
    let startIndex = str.rangeOfString("<mylabel>")!.last!
    let endIndex = str.rangeOfString("</mylabel>")!.first!
    print(str.substringWithRange(Range<String.Index>(start: startIndex.advancedBy(1), end: endIndex)))
    

    【讨论】:

      【解决方案3】:

      虽然你通常是would not want to use regular expressions to parse XML/HTML,但如果你知道它会有&lt;mylabel&gt;&lt;/mylabel&gt;,你可以这样做:

      let result = str.stringByReplacingOccurrencesOfString("<mylabel>(.*)</mylabel>", withString: "$1", options: .RegularExpressionSearch, range: nil)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-08
        • 1970-01-01
        • 2019-12-02
        • 2011-08-07
        • 1970-01-01
        相关资源
        最近更新 更多