import Foundation
// WARNING: You included a flag that Swift doesn't support: u
// When this flag is set, it makes the pattern and subject strings to be treated as unicode.
// Swift already treats the pattern and subject strings as unicode by default, so including this flag is redundant.
let pattern = #"\(groupid=\s+(?P<groupid>\d+)"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
seq_read_4k: (groupid= 0 jobs= 1): err= 0: pid= 7396: Wed Sep 2 14:07:25 2015
read : io= 72013 MB bw= 614510 KB/s iops= 153627 runt= 120001msec
--
seq_read_128k: (groupid= 1 jobs= 1): err= 0: pid= 7463: Wed Sep 2 14:07:25 2015
read : io= 74277 MB bw= 633821 KB/s iops= 4951 runt= 120001msec
--
rand_read_4k: (groupid= 2 jobs= 1): err= 0: pid= 7480: Wed Sep 2 14:07:25 2015
read : io= 4102.4 MB bw= 35006 KB/s iops= 8751 runt= 120001msec
--
rand_read_1M: (groupid= 3 jobs= 1): err= 0: pid= 7497: Wed Sep 2 14:07:25 2015
read : io= 44963 MB bw= 383678 KB/s iops= 374 runt= 120002msec
"""#
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