import Foundation
let pattern = #"(?:(?:\d[- _]*){6,})|(?<num_1>\d[- _]*)(?<num_2>\d[- _]*)(?<num_3>\d[- _]*)(?<num_4>\d)(?<num_5>[- _]*\d)?"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
"1-2-3-4-5-6" => no
"1-2-3-4-5" => yes match 1
"1-2-3-4" => yes match 2
"1-2-3" => no
"123456" => no
"12345" => yes match 3
"1234" => yes match 4
"123" => no
foo 123 56 78 bar
"0000" will become "****"
"any text 000 00 more texts" will become "any text ***** more texts"..notice that the space is removed
"any text 000 00 more texts 00" will become "any text ***** more texts 00"
"any text 000 00 more texts 00 00" will become "any text ***** more texts ****"
"any text 00-00 more texts 00_00" will become "any text **** more texts ****"
a 0 12345 fdf
"""#
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