String
NSRegularExpression を使用して画像の URL を取得したい。
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)
}
}
単純な文字列だけで機能しますが、HTML
String
.
作業例:
let tempString = "jhgsfjhgsfhjgajshfgjahksfgjhs http://jhsgdfjhjhggajhdgsf.jpg jahsfgh asdf ajsdghf http://jhsgdfjhjhggajhdgsf.png"
findURlUsingExpression(tempString)
出力:
http://jhsgdfjhjhggajhdgsf.jpg
http://jhsgdfjhjhggajhdgsf.png
しかし、これでは機能しません: http://www.writeurl.com/text/478sqami3ukuug0r0bdb/i3r86zlza211xpwkdf2m