You should consume as many characters up to the src
attribute as possible. You can do it with .*?
:
var regex: NSRegularExpression = NSRegularExpression(pattern: "<img.*?src=\"([^\"]*)\"", options: .CaseInsensitive, error: nil)!
Also, you can use the sample from Ross' iOS Swift blog
import Foundationextension 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 calling code:
var result = "<img.*?src=\"([^\"]*)\"".firstMatchIn(elementString, atRangeIndex: 1)
To make sure .
matches newline, use options: NSRegularExpressionOptions.DotMatchesLineSeparators
.