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.

Revisions

  1. hcrub revised this gist Apr 8, 2017. No changes.
  2. hcrub created this gist Apr 8, 2017.
    44 changes: 44 additions & 0 deletions NSRegularExpression+Split.swift
    Original 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
    }

    }