import Foundation
let pattern = #"^/(media/catalog/product/cache)/\d+/thumbnail/(\d+x\d+)/[a-z0-9]+/(\S+)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
/media/catalog/product/cache/1/thumbnail/543x403/db978388cfd007780066eaab38556cef/l/e/legal_slide01.jpg
# check if match with above:
/pub/media/catalog/product/cache/543x403/l/e/legal_slide01.jpg
/media/catalog/product/cache/1/thumbnail/543x403/db978388cfd007780066eaab38556cef/n/u/number1.png
# check if match with above:
/pub/media/catalog/product/cache/543x403/n/u/number1.png
"""##
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"/pub/$1/$2/$3"#
let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)
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