Getting img url from swift rss feed
I want to get the img url from part of a string.
Here is an example img url I'm trying to extract:
<p><img width="357" height="500" src="http://images.sgcafe.net/2015/05/OVA1-357x500.jpg" class="attachment- medium wp-post-image" alt="OVA1" />
My current implementation breaks down into textCheck
that speaks about it NIL
. I looked at the Objective C solution on stackoverflow and implemented it quickly, but it doesn't work.
var elementString = item.summary
var regex: NSRegularExpression = NSRegularExpression(pattern: "img src=\"([^\"]*)\"", options: .CaseInsensitive, error: nil)!
let range = NSMakeRange(0, count(elementString))
var textCheck = regex.firstMatchInString(elementString, options: nil, range: range)!
let text = (elementString as NSString).substringWithRange(textCheck.rangeAtIndex(1))
source to share
You should use as many characters as possible before the attribute src
. You can do it with .*?
:
var regex: NSRegularExpression = NSRegularExpression(pattern: "<img.*?src=\"([^\"]*)\"", options: .CaseInsensitive, error: nil)!
Alternatively, you can use the sample from Ross iOS Swift Blog
import Foundation
extension String {
func firstMatchIn(string: NSString!, atRangeIndex: Int!) -> String {
var error : NSError?
let re = NSRegularExpression(pattern: self, options: .CaseInsensitive, error: &error)
let match = re.firstMatchInString(string, options: .WithoutAnchoringBounds, range: NSMakeRange(0, string.length))
return string.substringWithRange(match.rangeAtIndex(atRangeIndex))
}
}
And in your codebase:
var result = "<img.*?src=\"([^\"]*)\"".firstMatchIn(elementString, atRangeIndex: 1)
To make sure it .
matches the newline use options: NSRegularExpressionOptions.DotMatchesLineSeparators
.
source to share