import Foundation
let pattern = #"<a\shref="\/vn\/tags\/.*?">(?P<tags>.*?)<\/a>"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"<ul class="clearfix"><li><span class="tagBoxTitle">Từ khóa: </span></li><li><a href="/vn/tags/Th%E1%BB%B1c%20ph%E1%BA%A9m/index.html">Thá»±c phẩm</a>, </li><li><a href="/vn/tags/gi%C3%A1-c%E1%BA%A3/index.html">giá-cả</a>, </li><li><a href="/vn/tags/h%C3%A0ng-ti%C3%AAu-d%C3%B9ng/index.html">hà ng-tiêu-dùng</a>, </li><li><a href="/vn/tags/gi%E1%BA%A3m-gi%C3%A1/index.html">giảm-giá</a>, </li><li><a href="/vn/tags/c%C6%B0%E1%BB%9Bc-v%E1%BA%ADn-t%E1%BA%A3i/index.html">cước-váºn-tải</a>, </li><li><a href="/vn/tags/gi%C3%A1-x%C4%83ng/index.html">giá-xăng</a>, </li><li><a href="/vn/tags/x%C4%83ng-d%E1%BA%A7u/index.html">xăng-dầu</a>, </li><li><a href="/vn/tags/h%C3%A0ng-h%C3%B3a/index.html">hà ng-hóa</a>, </li><li><a href="/vn/tags/CPI/index.html">CPI</a>, </li><li><a href="/vn/tags/T%E1%BA%BFt-nguy%C3%AAn-%C4%91%C3%A1n/index.html">Tết-nguyên-đán</a></li></ul>"#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression