如何通过Swift3将HTML字符串分成数组或字典?

时间:2018-03-07 09:10:39

标签: ios string swift3 nsarray nsdictionary

我从API获得了HTML字符串:

let a: String = "<a href="https://www.google.com.tw">https://www.google.com.tw </a>"
let b: String = "<a href="myAppName://app/user/aa3b77411825b88b318d77gg">@Tim </a>Hello Tim"
let c: String = "<a href="myAppName://app/user/aa3b77411825b88b318d77gg">@Tim </a><a href="https://www.google.com.tw">https://www.google.com.tw </a>"

let splitedArray1: [String] = a.componentsSeparatedByString("?????") //splited string which is the best 
let splitedArray2: [String] = b.componentsSeparatedByString("?????") //splited string which is the best
let splitedArray3: [String] = c.componentsSeparatedByString("?????") //splited string which is the best

我想从它们中分离链接并获取如下的数据

print(splitedArray1) //["https://www.google.com.tw","https://www.google.com.tw"]
print(splitedArray2) //["myAppName://app/user/aa3b77411825b88b318d77gg","@Tim ","Hello Tim"]
print(splitedArray3) //["myAppName://app/user/aa3b77411825b88b318d77gg","@Tim ","https://www.google.com.tw","https://www.google.com.tw "]

4 个答案:

答案 0 :(得分:1)

可能的解决方案:使用NSAttributedString然后枚举NSLinkAttributeName,如果没有,则表示没有链接标记,因此您只需保留&#34;字符串&#34 ;,否则,您添加链接,然后添加字符串。

快速写在游乐场:

let a: String = "<a href=\"https://www.google.com.tw\">https://www.google.com.tw </a>"
let b: String = "<a href=\"myAppName://app/user/aa3b77411825b88b318d77gg\">@Tim </a>Hello Tim"
let c: String = "<a href=\"myAppName://app/user/aa3b77411825b88b318d77gg\">@Tim </a><a href=\"https://www.google.com.tw\">https://www.google.com.tw </a>"

let values:[String] = [a, b, c]



for aHTMLString in values
{
    let attributedString = try! NSAttributedString.init(data: aHTMLString.data(using: .utf8)!,
                                                        options: [.documentType: NSAttributedString.DocumentType.html],
                                                        documentAttributes: nil)
    var retValues = [String]()
    attributedString.enumerateAttribute(.link,
                                        in: NSRange(location: 0, length: attributedString.string.count),
                                        options: [],
                                        using: { (attribute, range, pointerStop) in
                                            if let attribute = attribute as? URL
                                            {
                                                retValues.append(attribute.absoluteString)
                                            }
                                            let subString = (attributedString.string as NSString).substring(with: range)
                                            retValues.append(subString)
    })

    print("*** retValues: \(retValues)")
}

let targetResult1 = ["https://www.google.com.tw","https://www.google.com.tw"]
let targetResult2 = ["myAppName://app/user/aa3b77411825b88b318d77gg","@Tim ","Hello Tim"]
let targetResult3 = ["myAppName://app/user/aa3b77411825b88b318d77gg","@Tim ","https://www.google.com.tw","https://www.google.com.tw "]
print("targetResult1: \(targetResult1)")
print("targetResult2: \(targetResult2)")
print("targetResult3: \(targetResult3)")

输出:

*** retValues: ["https://www.google.com.tw/", "https://www.google.com.tw "]
*** retValues: ["myappname://app/user/aa3b77411825b88b318d77gg", "@Tim ", "Hello Tim"]
*** retValues: ["myappname://app/user/aa3b77411825b88b318d77gg", "@Tim ", "https://www.google.com.tw/", "https://www.google.com.tw "]
targetResult1: ["https://www.google.com.tw", "https://www.google.com.tw"]
targetResult2: ["myAppName://app/user/aa3b77411825b88b318d77gg", "@Tim ", "Hello Tim"]
targetResult3: ["myAppName://app/user/aa3b77411825b88b318d77gg", "@Tim ", "https://www.google.com.tw", "https://www.google.com.tw "]

存在细微差别,我复制了你的&#34;目标&#34; (splitArray),它在最后一个中缺少一个空格,我的代码往往会添加一个#&#34; /&#34;在链接上。

答案 1 :(得分:1)

我已创建此扩展程序以获取网址。

extension String {
  func getUrl() -> String? {
      let rss = self.split { (char) -> Bool in
          return char == ">"
      }
      if let final = rss.last?.split(separator: "<"), let first = final.first {
          return String(first)
      }
      return nil
  }

  var hrefUrl: String {
    let matchString = "=\""
    let arrComponents = self.components(separatedBy: matchString)
    if let first = arrComponents.last, let str = first.split(separator: "\"").first {

        return String(str)
    }
    return ""
  }
}

用法:

let a: String = "<a href=\"https://www.google.com.tw\">https://www.google.com.tw </a>"
a.getUrl()  //output: https://www.google.com.tw 

//or

a.hrefUrl //output: https://www.google.com.tw 

答案 2 :(得分:0)

没有库的简单解决方案 - 只需使用String.replaceOccurences(of:...替换奇数字符串,如href,a替换为split参数(如&#34; |&#34;)然后使用componentsSeparatedByString(&#) 34; |&#34;)获取你的组件。

答案 3 :(得分:0)

使用正则表达式提取URL。下面我写了代码片段。

        let text = "<a href=\"https://www.google.com\">"

        let regex = try! NSRegularExpression(pattern: "<a[^>]+href=\"(.*?)\"[^>]*>")
        let range = NSMakeRange(0, text.characters.count)
        let matches = regex.matches(in: text, range: range)
        for match in matches {
            let strURL = (text as NSString).substring(with: match.rangeAt(1))
            print(strURL)
        }