import Foundation
let pattern = #"^(ABC)_([0-9]{4})_([0-9]+\.[0-9]+\.[0-9]+)(_[a-zA-Z])?(_[a-zA-Z]+)?\.xyz$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
ABC_0000_0.0.0.xyz
Group 1 : ABC
Group 2 : 0000
Group 3 : 0.0.0
Group 4 : <empty>
Group 5 : <empty>
ABC_0001_0.1.0_N.xyz
Group 1 : ABC
Group 2 : 0001
Group 3 : 0.1.0
Group 4 : _N
Group 5 : <empty>
ABC_0002_1.1.2_foo.xyz
Group 1 : ABC
Group 2 : 0002
Group 3 : 1.1.2
Group 4 : <empty>
Group 5 : _foo
ABC_0002_42.42.42_N_bar.xyz
Group 1 : ABC
Group 2 : 0002
Group 3 : 42.42.42
Group 4 : _N
Group 5 : _bar
"""#
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