import Foundation
let pattern = #"<img[^>]*src="([^"]+)"[^>]*>|<a\b.+?</a>(*SKIP)(*F)"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive, .dotMatchesLineSeparators])
let testString = #"""
<img src="/img/file1.jpg" />
<a href="/img/file2.jpg"><img src="/img/file2.jpg" /></a>
<img src="/img/file3.jpg" />
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"<a href="$1">$0</a>"#
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