import Foundation
// WARNING: You included a flag that Swift doesn't support: U
// When this flag is set, it inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by '?'.
// As an alternative, this effect can also be achieved by setting a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).
let pattern = #"<([^<\/>]*)([^<\/>]*)>([\s]*?|(?R))<\/\1>"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive, .dotMatchesLineSeparators])
let testString = ##"""
<table>
<tr>
<th>Nome da Opção</th>
<th class="boxToolTip" title="O símbolo para PETRD197 Ex:19,7 é PETRD197">Código da Opção</th>
<th class="boxToolTip" title="PETRD197 Ex:19,7 está listado(a) no mercado Bovespa">Bolsa de Valores</th>
<th class="boxToolTip" title="">Tipo de Ativo</th>
<th class="boxToolTip" title="O código ISIN para PETRD197 Ex:19,7">Código ISIN do Ativo</th>
<th class="ColumnLast">Descrição da Opção</th>
</tr>
<tr class="odd">
<td align="center"><b>PETRD197 Ex:19,7 20/04/2020</b></td>
<td align="center"><b>PETRD197</b></td>
<td align="center"><b><a href='/bolsa-de-valores/bovespa' title='Bovespa'>Bovespa</a></b></td>
<td align="center"><span id="quoteElementPiece5" class="">Opção</span></td>
<td align="center"><span id="quoteElementPiece6" class="">BRPETR4D0UU5</span></td>
<td align="center">Opção de Compra Ex:19,7 Vencimento: Abril</td>
</tr>
</table>
</div>
<div class="TableElement">
<table>
<tr>
<th>Preço de Exercício (Strike)</th>
<th>Vencimento do Contrato</th>
<th>Dias até Vencimento</th>
<th>Tipo de Negócio</th>
<th>Estilo de Opção</th>
<th>Classif.</th>
<th>Valor Intrínsico da Opção</th>
<th class="ColumnLast">Valor Extrínsico da Opção</th>
</tr>
<tr class="odd">
<td align="center">19,70</td>
<td align="center">20/04/2020</td>
<td align="center">3 dias</td>
<td align="center">Call</td>
<td align="center">Americano</td>
<td align="center">OTM</td>
<td align="center">-3,59</td>
<td align="center">3,60</td>
</tr>
</table>
</div>
<div class="TableElement">
<table>
<tr>
<th class="boxToolTip" title="O preço para PETRD197 Ex:19,7 está em alta ou baixa?"> </th>
<th class="boxToolTip" title="Mudança no preço de PETRD197 Ex:19,7">Variação do Dia (p)</th>
<th class="boxToolTip" title="Variação no preço de PETRD197 Ex:19,7">Variação do Dia %</th>
<th class="boxToolTip" title="Preço atual de PETRD197 Ex:19,7">Último Preço</th>
<th class="boxToolTip" title="Menor preço para as ações de PETRD197 Ex:19,7 hoje">Preço Mínimo</th>
<th class="boxToolTip" title="Maior preço para as ações de PETRD197 Ex:19,7 hoje">Preço Máximo</th>
<th class="boxToolTip" title="Preço de abertura para PETRD197 Ex:19,7 hoje">Preço de Abertura</th>
<th class="boxToolTip" title="Preco de fechamento de PETRD197 Ex:19,7 ontem">Preço de Fechamento</th>
<th class="boxToolTip" class="ColumnLast" title="Último negócio para PETRD197 Ex:19,7">Hora <img title='' alt='' class='quotePageRTupgradeLink' href='#quotePageRTupgradeContainer' id='cautionImageEnt' src='/common/images/icons/caution_sign.gif'/></th>
</tr>
<tr class="odd">
<td align="center" class="change_arrow_fa"><span id="quoteElementPiece7" class="PriceTextUnchanged"><span class="fa fa-circle PriceTextUnchanged fa-fw"></span></span></td>
<td align="center" class="change"><span id="quoteElementPiece8" class="PriceTextUnchanged">0,00</span></td>
<td align="center" class="chgpct"><span id="quoteElementPiece9" class="PriceTextUnchanged">0,0%</span></td>
<td align="center" class="current_price"><span id="quoteElementPiece10" class="PriceTextUnchanged">0,01</span></td>
<td align="center"><span id="quoteElementPiece11" class="">0,01</span></td>
<td align="center"><span id="quoteElementPiece12" class="">0,01</span></td>
<td align="center"><span id="quoteElementPiece13" class="">0,01</span></td>
<td align="center"><span id="quoteElementPiece14" class="">0,01</span></td>
<td align="center"><span id="quoteElementPiece15" class="">10:00:00</span></td>
</tr>
</table>
</div>
<div class="TableElement">
<table>
<tr>
<th class="boxToolTip" title="O número total de negócios que foram executados para PETRD197 durante o pregão mais recente.">Número de Negócios</th>
<th class="boxToolTip" title="Volume total negociado para PETRD197 Ex:19,7 hoje">Volume de Ações Negociadas</th>
<th class="boxToolTip" title="">Preço Médio</th>
<th class="boxToolTip" title="O valor total financeiro para este ativo durante o pregão mais recente. Volume financeiro é um cálculo contínuo sobre todos os negócios do pregão. Para cada negócio no pregão você multiplica o preço pelo número de ativos negociados. Então some esse resultado para todos os negócios no pregão.">Volume Financeiro</th>
<th class="boxToolTip" title="O volume médio diário durante os últimos 30 dias negociados.">Volume médio</th>
<th class="boxToolTip" title="O valor mais baixo e mais alto que o ativo atingiu nas últimas 52 semanas">Últimas 52 Semanas</th>
</tr>
<tr class="odd">
<td align="center"><span id="quoteElementPiece16" class="">7</span></td>
<td align="center"><span id="quoteElementPiece17" class="">22.000</span></td>
<td align="center"><span id="quoteElementPiece18" class="PriceTextUnchanged"> 0,01</span></td>
<td align="center"></span><span id="quoteElementPiece19" class=""> 220</span></td>
<td align="center">-</td>
<td align="center">0,00 - 0,00</td>
</tr>
</table>
</div>
<div class="TableElement">
<table>
<tr>
<th class="boxToolTip" title="O horário do último negócio realizado">Último Negócio</th>
<th>Tipo de Negócio</th>
<th>Quantidade de Ações Negociadas</th>
<th class="boxToolTip" title="O último preço negociado para PETRD197 Ex:19,7 (PETRD197).">Preço Negociado</th>
<th class="ColumnLast">Moeda</th>
</tr>
<tr class="odd">
<td align="center"><span id="quoteElementPiece20" class="">10:33:55</span></td>
<td align="center"><span id="quoteElementPiece21" class=""></span></td>
<td align="center"><span id="quoteElementPiece22" class="">100</span></td>
<td align="center" onclick="javascript:location.href='/bolsa-de-valores/bovespa/petrd197-ex-19-7-PETRD197/negocios'" style="cursor:pointer;text-decoration:underline;color:black;"><span id="quoteElementPiece23" class="trdprice current_price PriceTextUnchanged"> 0,01</span></td>
<td align="center"><span id="quoteElementPiece24" class="">BRL</span></td>
</tr>
</table>
</div>
<div class="TableElement">
<table>
<tr>
<th>Setor da Empresa</th>
</tr>
<tr class="odd">
<td align="center">
<a href="/mundo/brasil/setores/mineracao-extracao-petroleo-gas/extracao-petroleo-gas">Petróleo, Gás e Biocombustíveis / Petróleo, Gás e Biocombustíveis / Exploração e/ou Refino</a>
</td>
</tr>
</table>
</div>
<div class="TableElement">
<table><tr><th>Anotações</th></tr><tr class='odd'><td><a href='#' role='login'>Clique aqui para escrever uma anotação sobre esse ativo.</a></td></tr></table>
"""##
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