import Foundation
let pattern = #"\[(b|i|u|h1|h2|h3|large|small|list|table|grid)\](?:((?!\[\/\1\]).)*?|(?R))*\[\/\1\]"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
[b]the problem is that my [i]regex[/i] stops at the [b]first matching closing tag[/b] instead of matching recursively as i [u]expect it to.[/u] [/b]
[i]regex[/i] stops at the [b]first matching closing tag[/b] instead of matching recursively as i [u]expect it to.[/u]
[a]ssss[a]sssss[/a]ss[/a]
[b]sss[/b]
[c]asdfasd[d]asdaf[/d]fasdf[/c]
[i]test test [i]as fd[/i]this should match the whole line[/i]
[i]test test[j]this should match the whole line[/j]test[/i]
[i] test [j]this should match the pair of 'i' tags and ignore the second 'j' tag [/i] [/j]
the below line should have three sets of matches: center, h3, and grid; it only matches the h3 and grid tags
[center][logo][/center][hr][hr][h3]header[/h3][/center][hr][hr][grid][row][cell][b]some label[/b][cell]: [date][/grid]
"""#
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