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)data-[^="]+?=".+(?=["]\s)")|((?<=\s)(?:data-[^=]+?)=".+?(?=>))|((?<=\s)(?:data-[^=]+?)="[^>]+?(?=>))"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = ##"<p><style type="text/css"><!--td {border: 1px solid #ccc;}br {mso-data-placement:same-cell;}--></style><span style="font-size:10pt;font-family:Calibri, Arial;" data-sheets-value="{"1":2,"2":"When doing a Future trade workflow, and selecting this Future asset to be traded on, a vos displayed showing that the Futures Type (which is the asset subtype) does not have Geneva ID on it. After some investigation, turns out that the actual Futures subtype list does not contain the list item \"Physical index future.\", which is currently showing for Asset ID 3175, as seen in attached Picture 2. "}" data-sheets-userformat="{"2":13249,"3":{"1":0},"9":0,"10":0,"11":4,"12":0,"15":"Calibri","16":10}">When doing a Future trade workflow, and selecting this Future asset to be traded on, a vos displayed showing that the Futures Type (which is the asset subtype) does not have Geneva ID on it. After some investigation, turns out that the actual Futures subtype list does not contain the list item "Physical index future.", which is currently showing for Asset ID 3175, as seen in attached Picture 2</span></p>"##
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