import Foundation
let pattern = #"(https?:\/\/[a-z0-9]+(?:[\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})(?=https?)(\S+)"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = #"""
hi, this is your link (but this one is bad formatted and useless):
https://www.test.comhttps://app.test.com/a/b/c/5e20bed422e7880012ba8acc/next?param=1?locale=2
but there is a good link too:
https://app.test.com/a/b/c/5e20bed422e7880012ba8acc/next?param=1?locale=2
and there are also other irrelevant links:
http://www.google.com
http://test.test.com
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #""#
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