import Foundation
let pattern = #"\<(ol)(?: .*?)?\>(?:[^\<]|\<(.*?)\>.*\<\/\2\>)*\<\/\1\>"#
let regex = try! NSRegularExpression(pattern: pattern, options: .dotMatchesLineSeparators)
let testString = #"""
<ol>kjkjkj
</ol>
<ol s>
<li>Table of Contents.....................CT.TS</li>
<li>Gamecube Controls.....................CN.GC</li>
<li>Nintendo 64 Controls..................CN.64</li>
<li>Walkthrough...........................01.00
<ol>
<li>Kokiri Forest...............01.01</li>
</ol>
</li>
<li>Sidequests & Minigames................02.00
<ol>
<li>Shooting Gallery............02.01</li>
</ol>
</li>
<li>Boss Guide............................03.00
<ol>
<li>Gohma.......................03.01</li>
<li>Final Boss [Second Form]....03.15</li>
</ol>
</li>
<li>Item Checklist........................04.00
<ol>
<li>Final Dungeon...............04.47</li>
</ol>
</li>
<li>Shop Inventory........................05.00
<ol>
<li>Kokiri Shop [Young].........05.01</li>
<li>Goron Shop [Adult]..........05.09</li>
</ol>
</li>
<li>Ocarina Notes.........................06.00
<ol><ol>sdsds</ol>
<li>Requ<ol></ol>iem of Spirit...........06.12</li>
</ol>
</li>
<li>Heart Containers......................07.00</li>
<li>Item List.............................15.00</li>
<li>Legal & Copyright.....................LE.AL</li>
<li>Credits & Thanks......................CR.DS</li>
</ol>
<ol><ol><ol><ol><ol></ol></ol></ol></ol></ol>
sdsd
k<ol>jlkjlkj
kjbkjh</ol>
"""#
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