import Foundation
let pattern = #"<li>(?>[^<]+|(<[uo]l)>|<(?!\/?li)[^>]*>|(?R))*<\/li>(?(1)|(*F))"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
<li>Hi</li> - Just some text, should ignore
<li><ul><li>hi</li></ul></li> - Directly in <li>
<li>Hi<ul><li>hi</li></ul></li> - Plain text before the nested list
<li><strong>Hi</strong><ul><li>hi</li></ul></li> - HTML content before the nested list
<ul><li>list item 1</li></ul>
<ul><li>list item 1</li><li><ol><li>2.1</li><li>2.2</li><li>2.3</li></ol></li><li>list item 3</li></ul>
<ul><li>list item 1</li><li>asdasdas<ol><li>2.1</li><li>2.2</li><li>2.3</li></ol></li><li>list item 3</li></ul>
<ul><li>list item 1</li><li><strong>asdasdas</strong><ol><li>2.1</li><li>2.2</li><li>2.3</li></ol></li><li>list item 3</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