import Foundation
let pattern = #"<([^> ]+)[^>]*>[^<]*<([^> ]+)[^>]*>({{.*}})<\/\2>[^<]*<\/\1>"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = ##"""
# <td><p>{{README.README}}</p></td>
# My soluction is independent of the HTML tags which make it very flexible.
# Work with javascript, python and php(probably you are using javascript).
#
# Alternative soluctions... copy and try!
# More expecific:
<([^> ]+)[^>]*>[^<]*<([^> ]+)[^>]*>({{custom.amountTable}})<\/\2>[^<]*<\/\1>
# More expecific and faster:
<(tr)[^>]*>[^<]*<(td)[^>]*>({{custom.amountTable}})<\/\2>[^<]*<\/\1>
<thead>
<tr style="background-color: #487cdb; text-align: center;">
<td style="width: 224px;">qwerqwerqwer</td>
<td style="width: 224px;">qwerqwerqwer</td>
<td style="width: 225px;">qwerqwerqwer</td>
</tr>
</thead>
<tbody>
<tr>
<td style="width: 224px;"> </td>
<td style="width: 224px;"> </td>
<td style="width: 225px;"> </td>
</tr>
<tr style="text-align: center;">
<td style="width: 224px;" colspan="3">{{custom.amountTable}}</td>
</tr>
<tr>
<td style="width: 224px;"> </td>
<td style="width: 224px;"> </td>
<td style="width: 225px;"> </td>
</tr>
</tbody>
</table>
# <td><p>{{HEY.FYI}}</p></td>
# I could make a function that generate the regex dinamicly, for example you
# could pass the expecific {{custom.property}} part
# and the level of HTML tags to match
# matchFunction('custom.amountTable', 2))
<tag whatever="property">
<anothertag>{{custom.whatever}}</anothertag>
</tag>
<td><p>{{custom.whatever}}</p></td>
#Junior Báez: https://www.linkedin.com/in/jrbaez01/
"""##
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