过滤字符串中的非汉字、字母、数字

1、过滤字符串中的非汉字、字母、数字

/************ 控制器的view 加载完毕 的时候调用 *****************************/
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *originalString = @"非汉字 !@##@¥、字母 adafsa、#@#@#¥数字 空 格121223123¥¥#";
    NSString *resultString = [self filterCharactor:originalString withRegex:@"[^a-zA-Z0-9u4e00-u9fa5\s+]"];
    
    NSLog(@"%@", resultString);
}
#pragma mark - ************************************ 逻辑调用备用 *************************************************
/************ 过滤字符串中的非汉字、字母、数字 *****************************/
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr {
    
    NSString *filterText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:filterText
                                                       options:NSMatchingReportCompletion
                                                         range:NSMakeRange(0, filterText.length)
                                                  withTemplate:@""];
    return result;
}

2、结果

原文地址:https://www.cnblogs.com/CH520/p/9771532.html