NSScanner can be used to detect whether the string contains the specified string, integer, floating point, special character,
NSString *str = @"abcd12.3<4b5bv99-9v6.7f=ff00";
NSScanner *scanner = [NSScanner scannerWithString:str];
NSString *temp = @"";
NSInteger index = 0;
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"=-<"];
//设置扫描忽略的字符集
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"="]];
//从位置0开始扫描,直到扫描结束,可获得匹配成功的字符
while (![scanner isAtEnd]) {
if ([scanner scanCharactersFromSet:charSet intoString:&temp]) {
NSLog(@"%@", temp);
}
index++;
[scanner setScanLocation:index];
}
//匹配到字符集中的任何一个字符,立即停止扫描,返回第一个匹配字符之前的字符串
if ([scanner scanUpToCharactersFromSet:charSet intoString:&temp]) {
NSLog(@"%@", temp);
}
//匹配字符串中的数字
while (![scanner isAtEnd]) {
int result = 0;
if ([scanner scanInt:&result]) {
NSLog(@"%zd", result);
NSNumber *number = [NSNumber numberWithInt:result];
index = index + number.stringValue.length;
[scanner setScanLocation:index];
}else {
index++;
[scanner setScanLocation:index];
}
}
//匹配字符串中的浮点数
while (![scanner isAtEnd]) {
float result = 0;
if ([scanner scanFloat:&result]) {
NSLog(@"%f", result);
NSNumber *number = [NSNumber numberWithFloat:result];
index = index + number.stringValue.length;
[scanner setScanLocation:index];
}else {
index++;
[scanner setScanLocation:index];
}
}
//匹配到字符串“b”后立即停止
BOOL flag = [scanner scanUpToString:@"b" intoString:&temp];