objective-c限制除了点和下划线的特殊字符的2个方法

标签: ios Objective-C
发布时间: 2013/3/4 10:59:05

方法一: 使用scaner(如果你坚持要自定义accetpable的字符)

NSString *yourString = @"tBe47s_-#h54df";
 
NSMutableString *resultString = [NSMutableString stringWithCapacity:yourString.length];
 
NSScanner *scanner = [NSScanner scannerWithString:yourString];
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."];
 
while ([scanner isAtEnd] == NO)
{
    NSString *buffer;
    if ([scanner scanCharactersFromSet:charSet intoString:&buffer])
        [resultString appendString:buffer];
    else
        [scanner setScanLocation:([scanner scanLocation] + 1)];
}
 
NSLog(@"result: %@", resultString);

方法二:正则表达式(iOS4.0以后适用,4之前要用第三方库)

NSString *yourString = @"tBe%#&4.7s_-#h5S4df";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:@"([^A-Za-z0-9_.])"
                              options:0
                              error:&error];
 
NSString *resString = [regex stringByReplacingMatchesInString:yourString options:0 range:NSMakeRange(0, yourString.length) withTemplate:@""];
NSLog(@"result: %@", resString);


赞助商