Forked from hcrub/NSRegularExpression+Split.swift
Created
September 19, 2021 08:51
-
-
Save ptrkstr/ccd8baed9f49d05e7f687b8868678293 to your computer and use it in GitHub Desktop.
Regular Expression "split" Implementation written for Swift 3.0+.
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
// 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment