import Foundation
let pattern = #"""
([^\/]+)\/?
"""#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
https://www.ducati.com/es/es/motocicletas/monster/monster-797
https://www.ducati.com/es/es/motocicletas/diavel/diavel-1260
https://www.ducati.com/es/es/motocicletas/hypermotard/hypermotard
https://www.ducati.com/es/es/motocicletas/hypermotard/hypermotard-950
https://www.ducati.com/es/es/motocicletas/monster/monster-1200
https://www.ducati.com/es/es/motocicletas/monster/monster-1200-25-anniversario
https://www.ducati.com/es/es/motocicletas/monster/monster-1200r
https://www.ducati.com/es/es/motocicletas/monster/monster-797
https://www.ducati.com/es/es/motocicletas/monster/monster-821
https://www.ducati.com/es/es/motocicletas/multistrada/multistrada-1260
https://www.ducati.com/es/es/motocicletas/multistrada/multistrada-1260-enduro
https://www.ducati.com/es/es/motocicletas/multistrada/multistrada-950
https://www.ducati.com/es/es/motocicletas/multistrada/multistrada-enduro
https://www.ducati.com/es/es/motocicletas/panigale/1299-panigale-r-final-edition
https://www.ducati.com/es/es/motocicletas/panigale/959-panigale
https://www.ducati.com/es/es/motocicletas/panigale/panigale-v4
https://www.ducati.com/es/es/motocicletas/panigale/panigale-v4-r
https://www.ducati.com/es/es/motocicletas/supersport/supersport
https://www.ducati.com/es/es/motocicletas/xdiavel/xdiavel
"""#
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