NSRegularExpression方式:
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
UPDATE
性能測試NSPredicate VS 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解決方案
多短? – fengd
發佈您到目前爲止所嘗試的內容。 – rmaddy
@fengd這應該是可定製的 – TUNER88