Created
August 2, 2011 14:53
-
-
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
This file contains 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
/*! | |
* 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