NSRegular表达方式:
NSString *text = @"Lorem Ipsum is simply dummy text of the printing and typesetting industry";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b\\w{1,4}\\b\\s?" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, [text length]) withTemplate:@""];
NSLog(@"Result: %@", modifiedString);
结果:
Lorem Ipsum simply dummy printing typesetting industry
更新
性能测试NSPredicate与NSRegularExpression
NSString *string = @"Lorem Ipsum is simply dummy text of the printing and typesetting industry";
// NSPredicate
NSDate *start1 = [NSDate date];
for (int i = 1; i <= 10000; i++)
{
NSArray *words = [string componentsSeparatedByString:@" "];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"length > 4"];
NSArray *largerWords = [words filteredArrayUsingPredicate:pred];
NSString *filteredString = [largerWords componentsJoinedByString:@" "];
}
NSDate *finsh1 = [NSDate date];
NSTimeInterval executionTime1 = [finsh1 timeIntervalSinceDate:start1];
NSLog(@"Execution Time NSPredicate: %f", executionTime1);
// NSRegularExpression
NSDate *start2 = [NSDate date];
for (int i = 1; i <= 10000; i++)
{
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b\\w{1,4}\\b\\s?" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
}
NSDate *finsh2 = [NSDate date];
NSTimeInterval executionTime2= [finsh2 timeIntervalSinceDate:start2];
NSLog(@"Execution Time NSRegularExpression: %f", executionTime2);
结果:
Execution Time NSPredicate: 0.246003
Execution Time NSRegularExpression: 0.594555
NSPredicate 解决方案比 NSRegularExpression 快得多
感谢@Alladinian 提供 NSPredicate 解决方案