swift 4 两种方式匹配文本中包含的URL链接

xiaoxiao2021-02-28  12

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) //利用NSDataDetector直接匹配出url链接 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 { //查找到的范围数量 // 0: 和匹配方案完全一致的字符串 // 1: ()中需要匹配的字符串 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 =================
转载请注明原文地址: https://www.6miu.com/read-2650281.html

最新回复(0)