swift 4 两种方式匹配文本中包含的URL链接
let content =
"分享发红包的风格白癜风蝙蝠侠发布大风风格的分公司的\n奋斗故事如果生日公司的人过<br/><img src=\"https://img.aifootball365.cn/product/community/images/20180518/1526627127931.png\"><br/><img src=\"https://img.aifootball365.cn/product/community/images/20180518/1526627132497.png\"><br/><img src=\"https://img.aifootball365.cn/product/community/images/20180518/1526627137298.png\">"
let regularRange = NSRange(location:
0, length: content.count)
guard
let detector =
try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
else {
return }
detector.enumerateMatches(
in: content, options: [], range: regularRange) { (textCheckingResult, falgs, nil)
in
print(textCheckingResult?.url ??
"没有链接")
}
let pattern =
"<img[^>]*?src=\"(.*?)\">"
guard
let regularExpression =
try? NSRegularExpression.init(pattern: pattern, options: .dotMatchesLineSeparators)
else {
return }
let regularResults = regularExpression.matches(
in: content, options: NSRegularExpression.MatchingOptions(rawValue:
0), range: regularRange)
for textCheckingResult
in regularResults {
for idx
in 0..<textCheckingResult.numberOfRanges {
let range = textCheckingResult.rangeAt(idx)
let subStr = (content
as NSString).substring(
with: range)
print(
"\(range)--\(subStr)")
}
}
print(
"=================")
https:/
/img.aifootball365.cn/product/community/images/20180518/1526627127931.png
https:/
/img.aifootball365.cn/product/community/images/20180518/1526627132497.png
https:/
/img.aifootball365.cn/product/community/images/20180518/1526627137298.png
{
40,
92}--<img src=
"https://img.aifootball365.cn/product/community/images/20180518/1526627127931.png">
{
50,
80}--
https:/
/img.aifootball365.cn/product/community/images/20180518/1526627127931.png
{
133,
92}--<img src=
"https://img.aifootball365.cn/product/community/images/20180518/1526627132497.png">
{
143,
80}--
https:/
/img.aifootball365.cn/product/community/images/20180518/1526627132497.png
{
226,
92}--<img src=
"https://img.aifootball365.cn/product/community/images/20180518/1526627137298.png">
{
236,
80}--
https:/
/img.aifootball365.cn/product/community/images/20180518/1526627137298.png
=================