Extract links from string optimization

前端 未结 7 1024
予麋鹿
予麋鹿 2021-01-03 05:21

I get data (HTML string) from website. I want to extract all links. I write function (it works), but it is so slow...

Can you help me to optimize it? What standard

7条回答
  •  失恋的感觉
    2021-01-03 05:33

    Like AdamPro13 said above using NSDataDetector you can easily get all the URLs, see it the following code :

    let text = "http://www.google.com. http://www.bla.com"
    let types: NSTextCheckingType = .Link
    var error : NSError?
    
    let detector = NSDataDetector(types: types.rawValue, error: &error)        
    var matches = detector!.matchesInString(text, options: nil, range: NSMakeRange(0, count(text)))
    
    for match in matches {
       println(match.URL!)
    }
    

    It outputs :

    http://www.google.com
    http://www.bla.com
    

    Updated to Swift 2.0

    let text = "http://www.google.com. http://www.bla.com"
    let types: NSTextCheckingType = .Link
    
    let detector = try? NSDataDetector(types: types.rawValue)
    
    guard let detect = detector else {
       return
    }
    
    let matches = detect.matchesInString(text, options: .ReportCompletion, range: NSMakeRange(0, text.characters.count))
    
    for match in matches {
        print(match.URL!)
    }
    

    Remember to use the guard statement in the above case it must be inside a function or loop.

    I hope this help.

提交回复
热议问题