问题描述
- 怎么限制除了点和下划线的特殊字符
-
怎么限制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);
时间: 2025-01-21 15:02:20