Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save royratcliffe/1120351 to your computer and use it in GitHub Desktop.
Save royratcliffe/1120351 to your computer and use it in GitHub Desktop.
Replaces all matches of a given regular expression in a given string using a given block
/*!
* Replaces all matches of a given regular expression in a given string using a
* given block to compute the replacement string for each match. The block
* accepts the match result, the progressively replaced string along with its
* progressive offset.
*/
NSString *RRReplaceRegularExpressionMatchesInString(NSRegularExpression *regex, NSString *string, NSString *(^replacementStringForResult)(NSTextCheckingResult *result, NSString *inString, NSInteger offset))
{
NSMutableString *mutableString = [string mutableCopy];
NSInteger offset = 0;
for (NSTextCheckingResult *result in [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])])
{
// Replaces the entire result range. However the results after matching
// have ranges in the index space of the original string. Offset the
// range to correct for progressive replacements.
NSRange resultRange = [result range];
resultRange.location += offset;
NSString *replacementString = replacementStringForResult(result, mutableString, offset);
[mutableString replaceCharactersInRange:resultRange withString:replacementString];
offset += [replacementString length] - resultRange.length;
}
return [mutableString copy];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment