iOS去除特殊字符

清除特殊字符

// 方法一  使用遍历截取
+ (NSString *)cleanSpecialCharacters:(NSString *)text {
    if (text == nil) {
        return @"";
    }
    NSString *strResult = nil;
    NSMutableString *originString = [text mutableCopy];
    NSCharacterSet *cs = [NSCharacterSet characterSetWithCharactersInString:@"~!@#$%^&*()+={}':;',[]\\.<>?~!¥%……*()+【】‘;:”“’。,、?——"];
    NSRange range;
    do {
        range=[originString rangeOfCharacterFromSet:cs options:NSLiteralSearch];
        if (range.location != NSNotFound) {
            [originString deleteCharactersInRange:range];// 删除range代表的字符集
        }
    } while (range.location != NSNotFound);
    strResult = [[NSString alloc] initWithString:originString];
    return strResult;
}


//方法二使用正则    建议使用此方法
+ (NSString *)cleanSpecialCharacters:(NSString *)text {
   if (text == nil) {
        return @"";
    }
    NSString *regexString = @"[\\\\`~!@#$%^&*()+=|{}':;',\\[\\].<>/?!¥%……()——【】‘;:”“’。,、?\"]";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:0 error:NULL];
    NSString *result = [regex stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, [text length]) withTemplate:@""];
    return result;
}

你可能感兴趣的:(iOS去除特殊字符)