import Foundation
let pattern = #"^[A-Z0-9]+(?:-[A-Z0-9]+)?(?:,[A-Z0-9]+(?:-[A-Z0-9]+)?)*$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
//Valid Values
D1
DF2,AB2
D1-2
A1, A2
D1 - 2
1 - FH15
1-R3
1,D2
1,H5,8,S4
1 , H5, 8, S4
1, D2, D6-8, 6-9
1,D2,D6-8,6-9,G2,8
1-D3,TT6-8
1-D3, TT6-8
1-3, VB8, 11-SD13, R15
//Invalid values
1*, 3
,1,F2
-1-TG3
12-D4,
D1-F2-
1- F2- 4
D10,/
1234s
F4-,8
4,-H5
D3-F-G7
D3 - F - G7
4 , - H5
1*,D
12 - D4
"""#
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