import Foundation
let pattern = #"^(XXS\/XS|XS\/S|S\/M|M\/L|L\/XL|XL\/XXL|XXS|XS|S|M|L|XL|XXL|\d{2}\.\d{1}|\d{2}|youth)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
XXS/XS - 27.5"
XS/S - 27.5"
S/M - 27.5"
M/L - 27.5"
M/L - 29"
L/XL - 27.5"
L/XL - 29"
XL/XXL - 29"
S
M
L
XL
XXL
XXS - 27.5"
XS - 27.5"
S - 27.5"
S - 29"
M - 27.5"
M - 29"
L - 29"
XL - 29"
45.5 - 650B
48 - 650B
50.5 - 700c
53 - 700c
55.5 - 700c
58 - 700c
60.5 - 700c
45.5
48
50.5
53
55.5
58
60.5
youth
"""#
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