import Foundation
let pattern = #"(?=^[A-Za-z\d -\/:-@[-`{-~À-ÿ]{8,30}$)^(?:[A-Za-z\d]*[ -\/:-@[-`{-~À-ÿ]){0,3}[A-Za-z\d]*$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
AABBCCDD
OK -- Match
aabbccdd
OK -- Match
11111111
OK -- Match
A1A1b2b2
OK -- Match
A@~D1dIo
OK -- Match
AAB BCC0
OK -- Match (1 special, it's okay)
AABBCC@@
OK -- Match (2 specials, it's okay)
AABB C
OK -- Match (3 specials, it's okay)
A@~` C:
OK -- Match (3 specials, it's okay)
AABB
OK -- Should't match and didn't match (Less than 8 symbols)
AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPP
OK -- Should't match and didn't match (More than 30 symbols)
AA@@@@BB
ERROR ! -- Shouldn't match (4 specials, it's forbidden)
AAB B
ERROR ! -- Shouldn't match (4 specials, it's forbidden)
AABB@@@@
ERROR ! -- Shouldn't match (4 specials, it's forbidden)
"""#
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