import Foundation
let pattern = #"^\d+$\n"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
278
00:15:13,442 --> 00:15:14,436
Mr. Burns,
279
00:15:14,454 --> 00:15:17,893
I came here because my brother
is about to be wrongfully convicted,
280
00:15:17,947 --> 00:15:19,514
and the man I'm looking for
281
00:15:19,542 --> 00:15:21,010
would help me find the truth.
282
00:15:21,038 --> 00:15:21,907
Don't you get it?
283
00:15:21,932 --> 00:15:23,918
I don't care who you are
or what you want.
284
00:15:25,167 --> 00:15:26,801
Now get lost.
285
00:15:29,102 --> 00:15:31,170
I think you just sent away
the first person
"""#
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