import Foundation
let pattern = #"(.*\d*[13579]\.article)|(.*[a-d|[f-m]$)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
*** Match odds or A-M
(.*\d*[13579]\.article)|(.*[a-d|[f-m]$)
https://edu.rsc.org/science-research/salt-crystal-grows-legs/4012581.article
edu.rsc.org/45.article
edu.rsc.org/weuvkee/a
edu.rsc.org/weuvkee/f
****** Don't match
https://edu.rsc.org/ideas/5-ways-to-explain-titration/4012500.article?utm_source=house-list&utm_medium=email&utm_campaign=monthly-alert
https://edu.rsc.org/feature/making-materials-from-biomass/4012606.article
https://edu.rsc.org/eic/classroy
https://edu.rsc.org/wibble/chips/stuff/science
edu.rsc.org
*** Match evens or N-Z
(.*\d*[02468]\.article)|(.*[n-z]$)
https://edu.rsc.org/ideas/5-ways-to-explain-titration/4012500.article?utm_source=house-list&utm_medium=email&utm_campaign=monthly-alert
https://edu.rsc.org/feature/making-materials-from-biomass/4012606.article
https://edu.rsc.org/eic/classroy
https://edu.rsc.org/wibble/chips/stuff/science
****** Don't match
https://edu.rsc.org/science-research/salt-crystal-grows-legs/4012581.article
edu.rsc.org/45.article
edu.rsc.org/weuvkee/a
edu.rsc.org/weuvkee/f
"""#
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