import Foundation
let pattern = #"(?<=\w{7}\s\[)[^\]]+"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
fifthrelease 566091c changes to labranges] (3rd revision) loaded
firstrelease 4a56940 [origin/firstrelease] change priority to 1100 for all OpenQuery DVPs
fourthrelease 2875c7b [origin/fourthrelease] all DVPs loaded (including new formulas); rev 21 CRF
main 566091c [origin/main] changes to labranges (3rd revision) loaded
secondrelease ff35618 [origin/secondrelease] fixed double SAE mail generated by AE_09
* sixthrelease 440478f [origin/sixthrelease] 4th lab revision processed and loaded
thirdrelease e3d7038 [origin/thirdrelease] LabRanges loaded
"""#
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