1、使用NSString自定义的方法
NSString* teststr = @"aaaak$kbbbbk$kcccc";
NSLog(@"%@",teststr);
NSMutableString* nsstrmutable = [[NSMutableString alloc] initWithString:teststr];
[nsstrmutable replaceOccurrencesOfString:@"k$k" withString:@"TTT" options:NSCaseInsensitiveSearch range:NSMakeRange(0,nsstrmutable.length)];
NSLog(@"%@",nsstrmutable);
输出:
2015-12-14 10:32:45.070 delcmd[823:285871] aaaak$kbbbbk$kcccc
2015-12-14 10:32:45.073 delcmd[823:285871] aaaaTTTbbbbTTTcccc
2、使用CFString
NSString* teststr = @"aaaak$kbbbbk$kcccc";
NSLog(@"%@",teststr);
CFStringRef cfstr = (__bridge CFStringRef) teststr;
CFMutableStringRef cfstrmutable = CFStringCreateMutableCopy(NULL,CFStringGetLength(cfstr),cfstr);
CFStringFindAndReplace(cfstrmutable,CFSTR("k$k"),CFSTR("TTT"),CFRangeMake(0,CFStringGetLength(cfstrmutable)),kcfCompareCaseInsensitive);
NSString* str = (__bridge NSString*) cfstrmutable;
CFRelease(cfstrmutable);
NSLog(@"%@",str);
2015-12-14 10:32:45.070 delcmd[823:285871] aaaak$kbbbbk$kcccc
2015-12-14 10:32:45.073 delcmd[823:285871] aaaaTTTbbbbTTTcccc
3、使用正则 匹配替换
NSString* teststr = @"aaaak$kbbbbk$kcccc";
NSLog(@"%@",teststr);
NSError* error = nil;
NSRegularExpression* exp = [[NSRegularExpression alloc] initWithPattern:@"(.*?)k\\$k(.*?)" options:NSRegularExpressionCaseInsensitive error:&error];
NSString* expstr = [exp stringByReplacingMatchesInString:teststr options:0 range:NSMakeRange(0,teststr.length) withTemplate:@"$1TTT$2"];
NSLog(@"%@",expstr);
2015-12-14 10:32:45.070 delcmd[823:285871] aaaak$kbbbbk$kcccc
2015-12-14 10:32:45.073 delcmd[823:285871] aaaaTTTbbbbTTTcccc