美文网首页iOS常用
Swift 字符串去掉特殊字符

Swift 字符串去掉特殊字符

作者: DamonLu | 来源:发表于2019-02-19 15:44 被阅读0次

    最近在项目遇到这样的需求:在校验字符串时,需要去掉其中的特殊字符和空格。首先想到的的就是用正则表达式

    正则
    正则.png
    使用
    • Swift 版本
      为了方便使用,给 String 添加扩展方法
    extension String {
        func deleteSpecialCharacters() -> String {
            let pattern: String = "[^a-zA-Z0-9\u{4e00}-\u{9fa5}]"
            let express = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
            return express.stringByReplacingMatches(in: self, options: [], range: NSMakeRange(0, self.count), withTemplate: "")
        }
    }
    //使用
    var str = " Hello, playgr《、/.,ou nd**123圣诞节付款 "
    print(str.deleteSpecialCharacters())
    //输出结果
    //Helloplayground123圣诞节付款
    
    • Objective-C 版本
      在 Objective-C 中,可对NSString 添加category,并在category中实习如下方法
    + (NSString *)deleteSpecialCharacters:(NSString *)targetString {
        if (targetString.length == 0 || !targetString) {
            return nil;
        }
        NSError *error = nil;
        NSString *pattern = @"[^a-zA-Z0-9\u4e00-\u9fa5]";//正则取反
        NSRegularExpression *regularExpress = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];//这个正则可以去掉所有特殊字符和标点
        NSString *string = [regularExpress stringByReplacingMatchesInString:targetString options:0 range:NSMakeRange(0, [targetString length]) withTemplate:@""];
        return string;
    }
    
    

    相关文章

      网友评论

        本文标题:Swift 字符串去掉特殊字符

        本文链接:https://www.haomeiwen.com/subject/qvqfyqtx.html