Created
November 21, 2014 04:04
-
-
Save kamimoo/f37ae269e8b8527f676d to your computer and use it in GitHub Desktop.
JSのString.prototype.replace()で関数を渡すのと同等の処理
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
- (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