快速从RSS提要获取img url [英] Getting img url from RSS feed swift
问题描述
我希望能够从一段字符串中检索 img url.
I want to be able to retrieve the img url from a piece of string.
这是我尝试检索的 img URL 示例:
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" />
我当前的实现在 textCheck
处崩溃,它说它的 NIL
.我查看了 stackoverflow 上的 Objective C 解决方案并快速实现了它,但它似乎不起作用.
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))
推荐答案
您应该使用尽可能多的字符,直到 src
属性.你可以用 .*?
:
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)!
此外,您可以使用 Ross 的 iOS Swift 中的示例博客
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))
}
}
在您的调用代码中:
var result = "<img.*?src=\"([^\"]*)\"".firstMatchIn(elementString, atRangeIndex: 1)
要确保 .
匹配换行符,请使用 options: NSRegularExpressionOptions.DotMatchesLineSeparators
.
To make sure .
matches newline, use options: NSRegularExpressionOptions.DotMatchesLineSeparators
.
这篇关于快速从RSS提要获取img url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!