3

I want to be able to retrieve the img url from a piece of string.

Here's a sample of the img URL that I'm trying to retrieve:

<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 implemention is crashing at textCheck which says its NIL. I looked over at the Objective C solution on stackoverflow and implemented it in swift, but it doesn't seem to 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))
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Wraithseeker
  • 1,884
  • 2
  • 19
  • 34

1 Answers1

3

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 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 calling code:

var result = "<img.*?src=\"([^\"]*)\"".firstMatchIn(elementString, atRangeIndex: 1)

To make sure . matches newline, use options: NSRegularExpressionOptions.DotMatchesLineSeparators.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563