2016-04-05 23 views
1

NSRegularExpression kullanarak görüntülerin URL'sini String'dan almak istiyorum.NSRegularExpression Swift kullanılarak String'den Dize Bul

func findURlUsingExpression(urlString: String){ 

    do{ 

     let expression = try NSRegularExpression(pattern: "\\b(http|https)\\S*(jpg|png)\\b", options: NSRegularExpressionOptions.CaseInsensitive) 

     let arrMatches = expression.matchesInString(urlString, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, urlString.characters.count)) 

     for match in arrMatches{ 

      let matchText = urlString.substringWithRange(Range(urlString.startIndex.advancedBy(match.range.location) ..< urlString.startIndex.advancedBy(match.range.location + match.range.length))) 
      print(matchText) 
     } 

    }catch let error as NSError{ 

     print(error.localizedDescription) 
    } 
} 

olurda ama HTMLString ile sadece basit dize ile çalışır.

Çalışma Örnek:

let tempString = "jhgsfjhgsfhjgajshfgjahksfgjhs http://jhsgdfjhjhggajhdgsf.jpg jahsfgh asdf ajsdghf http://jhsgdfjhjhggajhdgsf.png" 

findURlUsingExpression(tempString) 

Çıktı: ile çalışan

http://jhsgdfjhjhggajhdgsf.jpg 
http://jhsgdfjhjhggajhdgsf.png 

Ama bu bir: http://www.writeurl.com/text/478sqami3ukuug0r0bdb/i3r86zlza211xpwkdf2m

cevap

2

yardımcı olabilir eğer kendi regex rulo etmeyin o. En kolay ve en güvenli yol NSDataDetector'u kullanmaktır. NSDataDetector kullanarak, önceden oluşturulmuş, yoğun olarak kullanılan bir ayrıştırma aracından yararlanırsınız; , tarihleri, adresleri, bağlantılar: NSData​Detector

NSDataDetector NSRegularExpression bir alt sınıfı olan, ancak bunun yerine bir yoğun bakım desen üzerinde eşleme, bu yarı-yapılandırılmış bilgiyi algılar:

Burada üzerinde iyi bir yazı olduğunu telefon numaraları ve toplu taşıma bilgileri.

import Foundation 

let tempString = "jhgsfjhgsfhjgajshfgjahksfgjhs http://example.com/jhsgdfjhjhggajhdgsf.jpg jahsfgh asdf ajsdghf http://example.com/jhsgdfjhjhggajhdgsf.png" 

let types: NSTextCheckingType = [.Link] 
let detector = try? NSDataDetector(types: types.rawValue) 
detector?.enumerateMatchesInString(tempString, options: [], range: NSMakeRange(0, (tempString as NSString).length)) { (result, flags, _) in 
    if let result = result?.URL { 
    print(result) 
    } 
} 

// => "http://example.com/jhsgdfjhjhggajhdgsf.jpg" 
// => "http://example.com/jhsgdfjhjhggajhdgsf.png" 

örnek o siteden, bir bağlantı aramak için adapte olduğunu.

+0

Size bildirmeye çalışacağım! –

+0

Çalışıyor ama yanlış bağlantı döndürüyor - 'http://i-wallpapers.blogspot.com/2011/12/christmas-iphone-wallpapers.html ", imgurl: " http://2.bp.blogspot.com/- w6JW7Dif8kc/TvDIZcOX7nI/AAAAAAAAAQg/9-7TXCZlutM/s1600/iphone_christmas_wallpaper +% 25282% 2529.jpg' –

+0

Ayrıştırmaya çalıştığınız dize mi, yoksa ayrıştırmak için veri almak için ziyaret ettiğiniz bir site mi? – ColGraff