程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> ios-怎麼限制除了點和下劃線的特殊字符

ios-怎麼限制除了點和下劃線的特殊字符

編輯:編程綜合問答
怎麼限制除了點和下劃線的特殊字符

怎麼限制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;
        }
}

最佳回答:


我想了好半天,不知道怎麼回答好...因為方法太多了...
方法一: 使用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);
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved