import Foundation
let pattern = #"(?s)\biPhone:\n\n+(?:(?!\n\n).)+\bSerial Number: (\w+)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
USB:
USB 2.0 SuperSpeed Bus:
Host Controller Location: Built-in USB
Internal Memory Card Reader:
Product ID: 0x8406
Serial Number: 000000000820 //i dont want this
Built-In: Yes
USB 3.0 Hi-Speed Bus:
PCI Device ID: 0x8c31
iPhone:
Vendor ID: 0x05ac (Apple Inc.)
Version: 7.02
Serial Number: wea0aa752ada7722ac92575e98z2e89c691f4282 //i want this
Speed: Up to 480 Mb/sec
Manufacturer: Apple Inc.
Location ID: 0x14100000 / 9
Apple Internal Keyboard / Trackpad:
Product ID: 0x0262
Vendor ID: 0x05ac (Apple Inc.)
Location ID: 0x14c00000 / 3
Current Available (mA): 500
Current Required (mA): 40
Built-In: Yes
"""#
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