import Foundation
let pattern = #"^[1-9]\d{0,3} ?[a-zA-Z]?(?: ?[/-] ?[1-9]\d{0,3} ?[a-zA-Z]?)?$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##############"""
############# valid ##########
12
12a
12A
12 A
12 a
12 b
12 z
121 b
56/58
56/58a
56-58
56 - 58
56-58a
1234
1234 a
56/58a
18a - 19b
18a-19b
############# not valid ##########
12345
25-ab
12ü
12_
asdfghjklöqwertzuioyxcvbnm
12!"§$$%&/()
a2
a2
13àâäèéêë
0
123aaa123,
123 aaa 123
1 a 1
1a 1'
1a1
13àâäèéêë
00 a
a a
00a
0a
12 ab 12
"""##############
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