zoukankan      html  css  js  c++  java
  • iOS 中文字符判断 正则NSRegularExpression 谓词NSPredicate 和 NSRange

    废话不说,直接上代码

    #pragma mark - 中文字符判断
    
    
    // 正则匹配是否包含中文
    - (BOOL)validateContainsChinese:(NSString *)content
    {
        NSRegularExpression *regularexpression = [[NSRegularExpression alloc]
                                                  initWithPattern:@"^[u4e00-u9fa5]"
                                                  options:NSRegularExpressionCaseInsensitive
                                                  error:nil];
        return ([regularexpression numberOfMatchesInString:content
                                                   options:NSMatchingReportProgress
                                                   range:NSMakeRange(0, content.length)] > 0);
    }

    // 谓词匹配是否为全中文
    - (BOOL)validateAllChinese:(NSString *)content
    {
        NSString *regEx = @"^[u4e00-u9fa5]+$";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regEx];
        
        return [predicate evaluateWithObject:content];
    }

    // 谓词匹配包含中文
    - (BOOL)validateContainsChineseT:(NSString *)content
    {
        NSString *regEx = @".+[u4e00-u9fa5].+";  // @"^[u4e00-u9fa5].*" - ^为匹配中文开始
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regEx];
        
        return [predicate evaluateWithObject:content];
    }

    // 匹配包含中文:利用rangeOfString:option:直接查找
    - (BOOL)validateRangeContainsChinese:(NSString *)content
    {
        NSString *regEx = @".*[u4e00-u9fa5].*";
        NSRange range = [content rangeOfString:regEx options:NSRegularExpressionSearch];
        
        return range.length;
        
    }

    // 匹配全是中文:利用rangeOfString:option:直接查找
    - (BOOL)validateRangeAllChinese:(NSString *)content
    {
        NSString *regEx = @"^[u4e00-u9fa5]+S";
        NSRange range = [content rangeOfString:regEx options:NSRegularExpressionSearch];
        
        return range.length;
        
    }


  • 相关阅读:
    试图加载格式不正确的程序。 (异常来自 HRESULT:0x8007000B)
    git 撤销刚提交的 commint
    At least one cache should be provided per cache operation.
    @Primary注解
    怎么把sql server数据导入mysql本地数据库?
    应用程序已预编译,因此不允许使用目录“/App_Code/”
    SpringBoot学习笔记15——Dozer的使用用来两个对象之间属性转换的工具
    Invalid packaging for parent POM (pom.xml), must be "pom" but is "jar" @ pom.xml
    浏览器调试console的多种用法
    bug本天成,妙手偶得之。
  • 原文地址:https://www.cnblogs.com/pruple/p/7450654.html
Copyright © 2011-2022 走看看