Skip to content

Instantly share code, notes, and snippets.

@fra3il fra3il/0.m Secret
Last active Feb 3, 2016

Embed
What would you like to do?
[WP/1049] NSCharacterSet vs. NSRegularExpressionSearch vs. NSScanner
// NSCharacterSet
NSCharacterSet *allowedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"];
NSString *deviceNameString = [[[[UIDevice currentDevice] name] componentsSeparatedByCharactersInSet:[allowedCharacterSet invertedSet]] componentsJoinedByString:@""];
// NSRegularExpressionSearch
NSString *deviceNameString = [[UIDevice currentDevice] name];
NSString *regularExpressionString = @"([a-zA-Z0-9_-])+";
NSMutableString *resultString = [NSMutableString string];
NSInteger location = 0;
while (location < [deviceNameString length]) {
NSString *string = [deviceNameString substringFromIndex:location];
NSRange range = [string rangeOfString:regularExpressionString options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
[resultString appendString:[string substringWithRange:range]];
location += range.location + range.length;
} else {
break;
}
}
// NSScanner
NSString *deviceNameString = [[UIDevice currentDevice] name];
NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"];
charset = [charset invertedSet];
NSScanner *scanner = [NSScanner scannerWithString:deviceNameString];
NSString *tempString = nil;
NSString *resultString = [NSString string];
while(![scanner isAtEnd]) {
[scanner setCharactersToBeSkipped:charset];
[scanner charactersToBeSkipped];
[scanner scanUpToCharactersFromSet:charset intoString:&tempString];
if (tempString != nil) {
resultString = [resultString stringByAppendingString:tempString];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.