FoundationにはNSRegularExpressionクラス(iOS4以降)があり、これは便利な場合があります。ドキュメントから:
NSRegularExpressionの基本的なマッチングメソッドは、正規表現がターゲット文字列の一部と一致するたびに呼び出されるBlockオブジェクトをクライアントが提供できるようにするBlockイテレータメソッドです。すべての一致を配列、一致の総数、最初の一致、および最初の一致の範囲として返すための追加の便利なメソッドがあります。
例えば:
NSString *input = @"Hello, how are you today?";
// make a copy of the input string. we are going to edit this one as we iterate
NSMutableString *output = [NSMutableString stringWithString:input];
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"\\w+"
options:NSRegularExpressionCaseInsensitive
error:&error];
// keep track of how many additional characters we've added (1 per iteration)
__block NSUInteger count = 0;
[regex enumerateMatchesInString:input
options:0
range:NSMakeRange(0, [input length])
usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
// Note that Blocks in Objective C are basically closures
// so they will keep a constant copy of variables that were in scope
// when the block was declared
// unless you prefix the variable with the __block qualifier
// match.range is a C struct
// match.range.location is the character offset of the match
// match.range.length is the length of the match
NSString *matchedword = [input substringWithRange:match.range];
// the matched word with the length appended
NSString *new = [matchedword stringByAppendingFormat:@"%d", [matchedword length]];
// every iteration, the output string is getting longer
// so we need to adjust the range that we are editing
NSRange newrange = NSMakeRange(match.range.location+count, match.range.length);
[output replaceCharactersInRange:newrange withString:new];
count++;
}];
NSLog(@"%@", output); //output: Hello5, how3 are3 you3 today5?