@Parag componentsSeparatedByString
Bafna 和 @J Shapiro 建议的或NSRegularExpression
例如:
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
NSError *error = NULL;
NSString *searchText = @"542$764$231$DataEntry";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d{3})\\$" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:searchText options:0 range:NSMakeRange(0, [searchText length]) ];
printf("match count = %ld\n",numberOfMatches);
[regex enumerateMatchesInString:searchText
options:0
range:NSMakeRange(0,[searchText length])
usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
NSRange range = [match rangeAtIndex:1];
printf("match = %s\n",[[searchText substringWithRange:range] UTF8String]);
}];
}
}
在模式具有简单的重复定界符的情况下,这componentsSeparatedByString
可能是首选方法并且性能更高;但为了完整起见,我包括了这种方法。