因项目需要,微信呢称需要去掉表情字符。找了两三天的资料。终于有答案了。在此给各位分享下
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 = "[^\u0020-\u007e\u4e00-\u9fa5]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); return m.replaceAll("").trim(); }原文链接:https://www.f2er.com/cocos2dx/338439.html