import Foundation
let pattern = #"((http|https):(\/\/)|www\.)\w*\.*\-*[^(mysite.com)(theothermysite.net)]\w*\.?[^\s\t\r\n\"]*"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = #"""
www.demo.com
// End -->
http://www.foo.co.uk/
http://regexr.com/foo.html?q=bar
"https://mediatemple.net"
HTTP://mediatemple.net
<SOURCE src="https://12-lvdl.vimeo.com/01/1087/5/130436788/397857524.mp4?expires=1449922638&token=07929326b8cd27cd962f3" type="video/mp4">
href="http://www.testsite.net/dashboard/editor/uploads/image_uploads/2012/12/12/p6fdVfdfQv0CEhfTf8FHd3A7sNmXigy1K.jpg" width="100%">
href="http://mysite.com/mailer/themes/Theme1/img/IMG_0001"
href="http://theothermysite.net/mailer/themes/Theme1/img/IMG_0001"
www.theothermysite.net/mailer/themes/Theme1/img/IMG_0001
"""#
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