NSString批量替换字符串

前端之家收集整理的这篇文章主要介绍了NSString批量替换字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

猜你在找的正则表达式相关文章