Skip to content

Instantly share code, notes, and snippets.

@hcrub
Last active August 25, 2023 15:10
Show Gist options
  • Save hcrub/218e1d25f1659d00b7f77aebfcebf15a to your computer and use it in GitHub Desktop.
Save hcrub/218e1d25f1659d00b7f77aebfcebf15a to your computer and use it in GitHub Desktop.
Regular Expression "split" Implementation written for Swift 3.0+.
// 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
}
}
@ptrkstr
Copy link

ptrkstr commented Sep 19, 2021

Thanks for sharing this, works great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment