import Foundation
let pattern = ##"^(?<Scheme>[file|ftp|https{0,1}|ldap|telnet]+:\/{2})?(?<Subdomain>[a-zA-Z0-9-]{0,4}\.)?(?<Domain>\w+\.\w+\.?\w+\/)(?<Subdirectory>@[\w.]+\/)?(?<Path>[\w_~.-]+\/?[\w_-]+\/{0,1}?[\w_~.-]+)(?<Query>[%?&;].[\w&_~.=-]+)?(?<Fragment>#?[\/\w_-~.,=&-]+)?$"##
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
https://medium.com/@s.vive00/7-changes-i-experienced-after-going-1-week-without-added-sugar-9bc48b667f87?source=email-8f87fbd013ca-1581664260785-digest.weekly------0-58------------------2882ae9f_a61e_4d5c_9f87_24f3e0d54cc9-1-----§ionName=top
https://medium.com/@DrAyala/exercise-is-the-answer-heres-why-it-s-a-weight-loss-underperformer-8b64103b8c8f?source=email-8f87fbd013ca-1581664260785-digest.weekly------1-59------------------2882ae9f_a61e_4d5c_9f87_24f3e0d54cc9-1-----§ionName=top#Fragment-identifier
https://www.medium.com/@DrAyala/exercise-is-the-answer-heres-why-it-s-a-weight-loss-underperformer-8b64103b8c8f?source=email-8f87fbd013ca-1581664260785-digest.weekly------1-59------------------2882ae9f_a61e_4d5c_9f87_24f3e0d54cc9-1-----§ionName=top#Fragment-identifier
http://www.yoursite.com/path/to/file.mp3
http://example.com/data.csv#row=4
http://example.com/bar.webm#t=40,80&xywh=160,120,320,240
example.com/data.csv#row=4
example.co.uk/data.csv#row=4
"""##
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