import Foundation
let pattern = #"^.+\/(.+?)[\W|$]"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
/var/log/audit/audit.log
/var/log/audit/audit.log.1
/var/log/boot.log
/var/log/btmp
/var/log/btmp-20170401
/var/log/chrony
/var/log/cron
/var/log/cron-20170326
/var/log/cron-20170402
/var/log/cron-20170410
/var/log/cron-20170416
/var/log/anaconda
./var/log/anaconda/anaconda.log
./var/log/anaconda/ifcfg.log
./var/log/anaconda/journal.log
./var/log/anaconda/ks-script-XcavhD.log
./var/log/anaconda/packaging.log
./var/log/anaconda/program.log
./var/log/anaconda/storage.log
./var/log/anaconda/syslog
./var/log/anaconda/X.log
./var/log/audit
./var/log/audit/audit.log
./var/log/audit/audit.log.1
/var/log/httpd/error_log;
"""#
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