Last active
December 7, 2024 20:12
-
-
Save robertmryan/6b82411f6ea1d9f555255bf7a9471ceb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// modern syntax of `NSRegularExpression` | |
func splitedString(string: String, length: Int) -> [String] { | |
let regexString = "(\\d{1,\(length)})" | |
let nsstring = string as NSString | |
let regex = try! NSRegularExpression(pattern: regexString) | |
return regex | |
.matches(in: string, range: NSRange(string.startIndex..., in: string)) | |
.map { nsstring.substring(with: $0.range) } | |
} | |
// or to eliminate NS types | |
func splitedString(string: String, length: Int) -> [Substring] { | |
let regexString = "(\\d{1,\(length)})" | |
var substrings: [Substring] = [] | |
var searchStart: String.Index? = string.startIndex | |
repeat { | |
if let range = string.range(of: regexString, options: .regularExpression, range: searchStart!..<string.endIndex) { | |
substrings.append(string[range]) | |
searchStart = range.upperBound | |
} else { | |
searchStart = nil | |
} | |
} while searchStart != nil | |
return substrings | |
} | |
// or, to use the new `Regex` type: | |
import RegexBuilder | |
func splitedStringWithNewRegex(string: String, length: Int) -> [Substring] { | |
let regex = Regex { Repeat(.digit, 1...length) } | |
return string.matches(of: regex).map { | |
$0.0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment