2 for 2012 for_2012 于 2013.01.29 17:00 提问

怎么限制除了点和下划线的特殊字符

怎么限制UITextField 中的特殊字符?只保留点和下划线。我用了下面的代码,但是没有反应:

#define ACCEPTABLE_CHARECTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
         NSCharacterSet *acceptedInput = [NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS];
        if (![[string componentsSeparatedByCharactersInSet:acceptedInput] count] > 1){
            NSLog(@"not allowed");
            return NO;
        }
        else{
            return YES;
        }
}

1个回答

langyufei
langyufei   2013.01.31 00:45
已采纳

我想了好半天,不知道怎么回答好...因为方法太多了...
方法一: 使用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);
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!