import Foundation
let pattern = ##"#{(\w+[.\w+]+)\}"##
let regex = try! NSRegularExpression(pattern: pattern)
let testString = ##"The [#{product.name}](/card-details/card-name/#{details.slug.value}) which has an annual fee of #{details.annual_fee.value}, does double-duty as a rewards credit card and a balance transfer credit card. You’ll get a big sign-up bonus: Discover will automatically double cash back for new card holders in your first year. Plus, when you opt in to a bonus rewards program, this card earns 5% cash back on rotating bonus categories like gas and restaurants. Be aware that these 5% rewards are capped at $1,500 spent per quarter. On all other purchases, you’ll get 1% cash back. There is #{details.pros_bullets.value.1} and it comes with a generous 0% APR offer: #{details.apr_intro_message_list.value.0}. The card charges a 3% balance transfer fee, and Discover isn’t widely accepted abroad. But it could be a great choice if you’re trying to earn big rewards on new purchases while paying off an old debt."##
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