使用正则匹配去除所有字符串
+ (NSString *)deleteChineseStringWithString:(NSString *)string {
// for (int i=0; i < string.length; i++) {
// int utfCode = 0;
// void *buffer = &utfCode;
// NSRange range = NSMakeRange(i, 1);
// BOOL b = [string getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];
// if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5)) {
// string = [string stringByReplacingCharactersInRange:range withString:@""];
// }
// }
// return string;
// 创建匹配所有中文的正则表达式模式
NSString *pattern = @"[\\p{Han}]+";
// 使用正则表达式模式进行匹配
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
if (error) {
NSLog(@"正则表达式错误: %@", error);
}
// 执行匹配并替换为空字符串,得到去除中文后的结果
NSString *result = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, string.length) withTemplate:@""];
// 输出结果
NSLog(@"结果: %@", result); // 输出 "Hello word"
return result;
}
截取字符串中的所有汉字
- (NSString *)getSimpleChineseWithString:(NSString *)string
{
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < string.length; i++) {
int a = [string characterAtIndex:i];
if (a < 0x9fff && a > 0x4e00) {
[array addObject:[string substringWithRange:NSMakeRange(i, 1)]];
}
}
return [array componentsJoinedByString:@""];
}
判断是否有中文
-(BOOL)hasChinese {
for(int i=0; i< [self length];i++){
int a = [self characterAtIndex:i];
if( a > 0x4e00 && a < 0x9fff)
{
return YES;
}
}
return NO;
//有中文的链接处理
// str1 = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}