最近在项目中遇到过滤某些特殊字符和表情的需求,有正则表达式和NSCharacterSet两种方法可以实现此需求。
1 NSCharacterSet方法,详细的具体API请查阅文档。
- (NSString *)ttLegalNickName
{
//合法字符集合
NSCharacterSet *legalPunctuationCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@",.·,。•、"];
//英文和数字字符集合
NSCharacterSet *alphanumericCharacterSet = [NSCharacterSet alphanumericCharacterSet];
//中文字符集合
NSCharacterSet *chineseSet = [NSCharacterSet ttChineseSet];
//合法字符 英文和数字字符 中文字符 并集的集合
NSMutableCharacterSet *characterSet = [[NSMutableCharacterSet alloc] init];
[characterSet formUnionWithCharacterSet:legalPunctuationCharacterSet];
[characterSet formUnionWithCharacterSet:alphanumericCharacterSet];
[characterSet formUnionWithCharacterSet:chineseSet];
// 除去合法字符 英文和数字字符 中文字符 并集的集合的补集
NSCharacterSet *illegalCharacterSet = characterSet.invertedSet;
// 将非法字符过滤成 @""
NSString *legalNickName = [[self componentsSeparatedByCharactersInSet:illegalCharacterSet] componentsJoinedByString:@""];
// 将合法字符过滤成 @"·"
legalNickName = [[legalNickName componentsSeparatedByCharactersInSet:legalPunctuationCharacterSet] componentsJoinedByString:@"·" ];
return legalNickName;
}
+ (NSCharacterSet *)ttChineseSet
{
// 中文字符集合
static NSCharacterSet *chineseSet;
if (chineseSet == nil)
{
NSMutableCharacterSet *aCharacterSet = [[NSMutableCharacterSet alloc] init];
NSRange lcEnglishRange;
lcEnglishRange.location = (unsigned int)0x4e00;
lcEnglishRange.length = (unsigned int)0x9fa5 - (unsigned int)0x4e00;
[aCharacterSet addCharactersInRange:lcEnglishRange];
chineseSet = aCharacterSet;
}
return chineseSet;
}
以上可以根据自己的需求去灵活配置建立分类。
2 正则方法, 后续更新