How can I split the given String
in Swift into groups with given length, reading from right to left?
For example, I have string 123456789
a
Here is a version using NSRegularExpressions
func splitedString(string: String, length: Int) -> [String] {
var groups = [String]()
let regexString = "(\\d{1,\(length)})"
do {
let regex = try NSRegularExpression(pattern: regexString, options: .CaseInsensitive)
let matches = regex.matchesInString(string, options: .ReportCompletion, range: NSMakeRange(0, string.characters.count))
let nsstring = string as NSString
matches.forEach {
let group = nsstring.substringWithRange($0.range) as String
groups.append(group)
}
} catch let error as NSError {
print("Bad Regex Format = \(error)")
}
return groups
}