如何从 Swift 中的 RSS 获取 "src" 字符串?
How can i get "src" string from RSS in Swift?
我有一个带有 html 标签的 RSS 页面,如下所示:
<description>
<![CDATA[
<a href='https://www.24h.com.vn/bong-da/psg-trao-than-dong-mbappe-sieu-luong-bong-chi-kem-messi-real-vo-mong-c48a1112120.html' title='PSG trao thần đồng Mbappe siĂªu lÆ°Æ¡ng bổng: Chỉ kĂ©m Messi, Real vỡ má»™ng'><img width='130' height='100' src='https://image.24h.com.vn/upload/4-2019/images/2019-12-27/1577463916-359-thumbnail.jpg' alt='PSG trao thần đồng Mbappe siĂªu lÆ°Æ¡ng bổng: Chỉ kĂ©m Messi, Real vỡ má»™ng' title='PSG trao thần đồng Mbappe siĂªu lÆ°Æ¡ng bổng: Chỉ kĂ©m Messi, Real vỡ má»™ng' /></a><br />PSG trong ná»— lá»±c giữ chĂ¢n “sĂ¡t thủ†Kylian Mbappe, sẵn sĂ ng tăng lÆ°Æ¡ng khổng lồ - má»™t Ä‘á»™ng thĂ¡i nhằm xua Ä‘uổi Real Madrid.
]]>
</description>
请帮助我如何获取 src
的值来显示图像。我也尝试 但它不起作用。这是我获取 src 的代码(代码总是 运行 image = "nil"
):
let regex: NSRegularExpression = try! NSRegularExpression(pattern: "<img.*?src=\"([^\"]*)\"", options: .caseInsensitive)
let range = NSMakeRange(0, description.count)
if let textCheck = regex.firstMatch(in: description, options: .withoutAnchoringBounds, range: range) {
let text = (description as NSString).substring(with: textCheck.range(at: 1))
image = text
} else {
image = "nil"
}
感谢您的帮助!
您需要更改正则表达式以匹配单引号,而不仅仅是双引号,因为您尝试解析的 html 字符串包含单引号,而不是像一个在链接的问答中。
let regex: NSRegularExpression = try! NSRegularExpression(pattern: "<img.*?src=[\"\']([^\"\']*)[\"\']", options: .caseInsensitive)
如果您确定只需要匹配单引号,可以通过将 [\"\']
替换为 \'
来简化模式。目前,正则表达式模式将匹配单引号和双引号。
我有一个带有 html 标签的 RSS 页面,如下所示:
<description>
<![CDATA[
<a href='https://www.24h.com.vn/bong-da/psg-trao-than-dong-mbappe-sieu-luong-bong-chi-kem-messi-real-vo-mong-c48a1112120.html' title='PSG trao thần đồng Mbappe siĂªu lÆ°Æ¡ng bổng: Chỉ kĂ©m Messi, Real vỡ má»™ng'><img width='130' height='100' src='https://image.24h.com.vn/upload/4-2019/images/2019-12-27/1577463916-359-thumbnail.jpg' alt='PSG trao thần đồng Mbappe siĂªu lÆ°Æ¡ng bổng: Chỉ kĂ©m Messi, Real vỡ má»™ng' title='PSG trao thần đồng Mbappe siĂªu lÆ°Æ¡ng bổng: Chỉ kĂ©m Messi, Real vỡ má»™ng' /></a><br />PSG trong ná»— lá»±c giữ chĂ¢n “sĂ¡t thủ†Kylian Mbappe, sẵn sĂ ng tăng lÆ°Æ¡ng khổng lồ - má»™t Ä‘á»™ng thĂ¡i nhằm xua Ä‘uổi Real Madrid.
]]>
</description>
请帮助我如何获取 src
的值来显示图像。我也尝试 image = "nil"
):
let regex: NSRegularExpression = try! NSRegularExpression(pattern: "<img.*?src=\"([^\"]*)\"", options: .caseInsensitive)
let range = NSMakeRange(0, description.count)
if let textCheck = regex.firstMatch(in: description, options: .withoutAnchoringBounds, range: range) {
let text = (description as NSString).substring(with: textCheck.range(at: 1))
image = text
} else {
image = "nil"
}
感谢您的帮助!
您需要更改正则表达式以匹配单引号,而不仅仅是双引号,因为您尝试解析的 html 字符串包含单引号,而不是像一个在链接的问答中。
let regex: NSRegularExpression = try! NSRegularExpression(pattern: "<img.*?src=[\"\']([^\"\']*)[\"\']", options: .caseInsensitive)
如果您确定只需要匹配单引号,可以通过将 [\"\']
替换为 \'
来简化模式。目前,正则表达式模式将匹配单引号和双引号。