Skip to content

Instantly share code, notes, and snippets.

@kamimoo
Created November 21, 2014 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamimoo/f37ae269e8b8527f676d to your computer and use it in GitHub Desktop.
Save kamimoo/f37ae269e8b8527f676d to your computer and use it in GitHub Desktop.
JSのString.prototype.replace()で関数を渡すのと同等の処理
- (NSString *)stringByReplacingPattern:(NSString *)patternString usingBlock:(NSString *(^)(NSTextCheckingResult *match))replacer {
if (!replacer) {
return nil;
}
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:patternString
options:NSRegularExpressionAnchorsMatchLines
error:NULL];
__block NSMutableString *converted = [NSMutableString string];
__block NSUInteger position = 0;
[regex enumerateMatchesInString:self
options:0
range:NSMakeRange(0, self.length)
usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
NSRange range = [match rangeAtIndex:0];
// マッチした部分までの文字列を追加
[converted appendString:[self substringWithRange:NSMakeRange(position, range.location - position)]];
// マッチした部分は変換
[converted appendString:replacer(match)];
position = range.location + range.length;
}];
if (position < self.length) {
[converted appendString:[self substringFromIndex:position]];
}
return converted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment