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?