Last active
August 25, 2023 15:10
-
-
Save hcrub/218e1d25f1659d00b7f77aebfcebf15a to your computer and use it in GitHub Desktop.
Revisions
-
hcrub revised this gist
Apr 8, 2017 . No changes.There are no files selected for viewing
-
hcrub created this gist
Apr 8, 2017 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,44 @@ // NSRegularExpression+Split.swift // // Verbatim ObjC->Swift port originating from https://github.com/bendytree/Objective-C-RegEx-Categories extension NSRegularExpression { func split(_ str: String) -> [String] { let range = NSRange(location: 0, length: str.characters.count) //get locations of matches var matchingRanges: [NSRange] = [] let matches: [NSTextCheckingResult] = self.matches(in: str, options: [], range: range) for match: NSTextCheckingResult in matches { matchingRanges.append(match.range) } //invert ranges - get ranges of non-matched pieces var pieceRanges: [NSRange] = [] //add first range pieceRanges.append(NSRange(location: 0, length: (matchingRanges.count == 0 ? str.characters.count : matchingRanges[0].location))) //add between splits ranges and last range for i in 0..<matchingRanges.count { let isLast = i + 1 == matchingRanges.count let location = matchingRanges[i].location let length = matchingRanges[i].length let startLoc = location + length let endLoc = isLast ? str.characters.count : matchingRanges[i + 1].location pieceRanges.append(NSRange(location: startLoc, length: endLoc - startLoc)) } var pieces: [String] = [] for range: NSRange in pieceRanges { let piece = (str as NSString).substring(with: range) pieces.append(piece) } return pieces } }