Skip to content

Instantly share code, notes, and snippets.

@lludo
Created November 6, 2014 21:37
Show Gist options
  • Select an option

  • Save lludo/b5ba9836680e32678006 to your computer and use it in GitHub Desktop.

Select an option

Save lludo/b5ba9836680e32678006 to your computer and use it in GitHub Desktop.
String extension that returns a new string with matches of a regex replaced by a transformation
extension String {
func replace(regularExpression: NSRegularExpression, transform: (String) -> String) -> String {
var output = ""
var lastMatchedLocation = self.startIndex
let rangeAll = NSMakeRange(0, countElements(self));
regularExpression.enumerateMatchesInString(self, options: NSMatchingOptions(0), range: rangeAll) {
(result: NSTextCheckingResult!, _, _) in
// Result matched range
let start = advance(self.startIndex, result.range.location)
let end = advance(start, result.range.length)
let matchedRange = Range(start: start, end: end)
// Range of the unmatched string preceding
let unmatchedPrecedingRange = Range(start: lastMatchedLocation, end: start)
lastMatchedLocation = end
// Add the transformed string to the output
let unmatchedPrecedingString = self.substringWithRange(unmatchedPrecedingRange)
let matchedTransformedString = transform(self.substringWithRange(matchedRange))
output += unmatchedPrecedingString + matchedTransformedString
}
// Add the unmatched remaining to the output
let unmatchedRemainingRange = Range(start: lastMatchedLocation, end: self.endIndex)
let unmatchedRemainingString = self.substringWithRange(unmatchedRemainingRange)
output += unmatchedRemainingString
return output
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment