import Foundation
let pattern = #"<dl>(?:[^<]+|<(?!/?dl\b)|(?R))*+</dl>"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive, .dotMatchesLineSeparators])
let testString = #"""
<p>
<span style="visibility:hidden" id="Synonyme">
<span id="Anker:Synonyme"></span>
</span>
</p>
<div style="margin-bottom:-0.5em; font-weight:bold;" title="bedeutungsgleich gebrauchte Wörter">Synonyme:</div>
<dl>
<dd>[1] <a href="/w/index.php?title=Blutsverwandte&action=edit&redlink=1" class="new" title="Blutsverwandte (Seite nicht vorhanden)">Blutsverwandte</a>,
<a href="/wiki/Sippe" title="Sippe">Sippe</a>
<dl>
<dd>[1a] <a href="/wiki/Kernfamilie" title="Kernfamilie">Kernfamilie</a></dd>
<dd>[1b] <i>abwertend, salopp:</i> <a href="/wiki/Mischpoke" title="Mischpoke">Mischpoke</a></dd>
</dl>
</dd>
<dd>[2] <a href="/wiki/Abart" title="Abart">Abart</a>,
<a href="/wiki/Art" title="Art">Art</a>,
<a href="/wiki/Bereich" title="Bereich">Bereich</a>,
<a href="/wiki/Departement" title="Departement">Departement</a>,
<a href="/wiki/Dialekt" title="Dialekt">Dialekt</a>,
<a href="/wiki/Fach" title="Fach">Fach</a>,
<a href="/wiki/Gattung" title="Gattung">Gattung</a>,
<a href="/wiki/Genus" title="Genus">Genus</a>,
<a href="/wiki/Geschlecht" title="Geschlecht">Geschlecht</a>,
<a href="/wiki/Gruppe" title="Gruppe">Gruppe</a>,
<a href="/wiki/Kategorie" title="Kategorie">Kategorie</a>,
<a href="/wiki/Linie" title="Linie">Linie</a>,
<a href="/wiki/Rasse" title="Rasse">Rasse</a>,
<a href="/wiki/Reihe" title="Reihe">Reihe</a>,
<a href="/wiki/Rubrik" title="Rubrik">Rubrik</a>,
<a href="/wiki/Schlag" title="Schlag">Schlag</a>
</dd>
</dl>
"""#
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