import Foundation
let pattern = #"(?i)^(?:NPO|PRO|PCR|REQ|8)+(\d{7,8})(?!(\d))"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
NPO1234567
NPO12345678
NPO123456
NPO123456789
npo1234567
npo12345678
npo123456
npo123456789
PRO1234567
PRO12345678
PRO123456
PRO123456789
pro1234567
pro12345678
pro123456
pro123456789
PCR1234567
PCR12345678
PCR123456
PCR123456789
pcr1234567
pcr12345678
pcr123456
pcr123456789
REQ1234567
REQ12345678
REQ123456
REQ123456789
req1234567
req12345678
req123456
req123456789
81234567
812345678
8123456
8123456789
"""#
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