因项目需求,微信呢称中需要去掉特殊。直接上代码了。希望对大家有帮助
ios版:
const char* IosHelper::removeEmoji(const char* str) { std::string strLen = str; NSString* username = [[NSString alloc] initWithBytes:str length:strLen.length() encoding:NSUTF8StringEncoding]; cocos2d::log("IosHelper::removeEmoji username0 = %s",str); NSLog(@"IosHelper::removeEmoji username1 = %@",username); //NSString *regex = @"^[a-zA-Z0-9_\u4e00-\u9fa5]+$"; NSString *regex = @"[\u0020-\u007e\u4e00-\u9fa5]"; //NSString *regex = @"^[a-zA-Z\u4e00-\u9fa5]+"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex]; NSString *temp = nil; //NSLog(@"IosHelper::removeEmoji username = %d",[username length]); for(int i = 0; i < [username length]; i++) { temp = [username substringWithRange:NSMakeRange(i,1)]; //NSLog(@"i = %d char = %x str = %@",i,temp,temp); if ([predicate evaluateWithObject:temp]) { //NSLog(@"This character is OK"); } else { NSRange range = NSMakeRange(i,1); username = [username stringByReplacingCharactersInRange:range withString:@" "]; } } NSString *withoutEmojiUsername = [username stringByReplacingOccurrencesOfString:@" " withString:@""]; NSLog(@"IosHelper::removeEmoji username2 = %@",withoutEmojiUsername); const char* retStr = [withoutEmojiUsername UTF8String]; cocos2d::log("IosHelper::removeEmoji username3 = %s",retStr); return retStr; }android
public static String RemoveEmoji(String str) { //String regEx = "[^A-Za-z0-9\u4e00-\u9fa5]"; String regEx = "[^\u0020-\u007e\u4e00-\u9fa5]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); return m.replaceAll("").trim(); }