下面是一個使用NSRegularExpression
的答案:
NSString * input = @"{{83}} fjsdkfjds {{122}}";
NSMutableString * strToMakeReplacements = [[NSMutableString alloc] initWithString:input];
NSError * error = nil;
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{([1-9]|[1-9][0-9]|[1-9][0-9][0-9])\\}\\}" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray * matches = [regex matchesInString:input options:NSMatchingReportProgress range:NSMakeRange(0, [input length])];
for (int i = [matches count]-1; i>=0 ; i--) {
NSTextCheckingResult * match = [matches objectAtIndex:i];
NSRange matchRange = match.range;
NSString * numString = [input substringWithRange:NSMakeRange(matchRange.location+2, matchRange.length-4)];
NSInteger num = [numString intValue];
NSString * replacementValue = [self replacementValueForNum:num]; // write this function yourself
[strToMakeReplacements replaceCharactersInRange:match.range withString:replacementValue];
}
請注意,您需要升級PE斜線在你的正則表達式,使之成爲\\{\\{([1-9]|[1-9][0-9]|[1-9][0-9][0-9])\\}\\}
輸入字符串的格式是什麼?你可以使用[NSString componentsSeparatedByString:]? – thelaws