No need for a regular expression, you could use the link property of an attributed string.
First, let's use this extension:
extension String{
func convert2Html() -> NSAttributedString {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
let htmlAttrib = NSAttributedString.DocumentType.html
return try NSAttributedString(data: data,
options: [.documentType : htmlAttrib],
documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
}
to convert this String
:
let html = "<a href = "https://mitsui-shopping-park.com/lalaport/koshien/" target="_blank"> https://mitsui-shopping-park.com/lalaport / koshien / </a>"
to an NSAttributedString
:
let attrib = html.convert2Html()
And then extract the link this way :
let link = attrib.attribute(.link, at: 0, effectiveRange: nil)
if let url = link as? NSURL, let href = url.absoluteString {
print(href) //https://mitsui-shopping-park.com/lalaport/koshien/
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…