简述:Cocoa框架中的NSPredicate用于查询,原理和用法都类似于SQL中的where,作用相当于数据库的过滤取。

定义(最常用到的方法):

[cpp] view plaincopy
  1. NSPredicate *ca = [NSPredicate predicateWithFormat:(NSString *), ...];

Format:
(1)比较运算符>,<,==,>=,<=,!=
可用于数值及字符串
例:@"number > 100"

(2)范围运算符:IN、BETWEEN
例:@"number BETWEEN {1,5}"
      @"address IN {'shanghai','beijing'}"

(3)字符串本身:SELF 
例:@“SELF == ‘APPLE’"

(4)字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
例:@"name CONTAIN[cd] 'ang'"   //包含某个字符串
       @"name BEGINSWITH[c] 'sh'"     //以某个字符串开头
       @"name ENDSWITH[d] 'ang'"      //以某个字符串结束
        注:[c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写,也不区分发音符号。

(5)通配符:LIKE
例:@"name LIKE[cd] '*er*'"    //*代表通配符,Like也接受[cd].
       @"name LIKE[cd] '???er*'"

(6)正则表达式:MATCHES
例:NSString *regex = @"^A.+e$";   //以A开头,e结尾
      @"name MATCHES %@",regex

实际应用:
(1)对NSArray进行过滤

[cpp] view plaincopy
  1. NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];
  2. NSString *string = @"ang";
  3. NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",string];
  4. NSLog(@"%@",[array filteredArrayUsingPredicate:pred]);

(2)判断字符串首字母是否为字母:

[cpp] view plaincopy
  1. NSString *regex = @"[A-Za-z]+";
  2. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
  3. if ([predicate evaluateWithObject:aString]) {
  4. }

(3)字符串替换:

[cpp] view plaincopy
  1. NSError* error = NULL;
  2. NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"(encoding=\")[^\"]+(\")"
  3. options:0
  4. error:&error];
  5. NSString* sample = @"<xml encoding=\"abc\"></xml><xml encoding=\"def\"></xml><xml encoding=\"ttt\"></xml>";
  6. NSLog(@"Start:%@",sample);
  7. NSString* result = [regex stringByReplacingMatchesInString:sample
  8. options:0
  9. range:NSMakeRange(0, sample.length)
  10. withTemplate:@"$1utf-8$2"];
  11. NSLog(@"Result:%@", result);

(4)截取字符串如下:

[cpp] view plaincopy
  1. //组装一个字符串,需要把里面的网址解析出来
  2. NSString *urlString=@"<meta/><link/><title>1Q84 BOOK1</title></head><body>";
  3. //NSRegularExpression类里面调用表达的方法需要传递一个NSError的参数。下面定义一个
  4. NSError *error;
  5. //http+:[^\\s]* 这个表达式是检测一个网址的。(?<=title\>).*(?=</title)截取html文章中的<title></title>中内文字的正则表达式
  6. NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=title\\>).*(?=</title)" options:0 error:&error];
  7. if (regex != nil) {
  8. NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
  9. if (firstMatch) {
  10. NSRange resultRange = [firstMatch rangeAtIndex:0];
  11. //从urlString当中截取数据
  12. NSString *result=[urlString substringWithRange:resultRange];
  13. //输出结果
  14. NSLog(@"->%@<-",result);
  15. }
  16. }

(5)判断手机号码,电话号码函数

[cpp] view plaincopy
  1. // 正则判断手机号码地址格式
  2. - (BOOL)isMobileNumber:(NSString *)mobileNum
  3. {
  4. /**
  5. * 手机号码
  6. * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
  7. * 联通:130,131,132,152,155,156,185,186
  8. * 电信:133,1349,153,180,189
  9. */
  10. NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
  11. /**
  12. 10         * 中国移动:China Mobile
  13. 11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
  14. 12         */
  15. NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
  16. /**
  17. 15         * 中国联通:China Unicom
  18. 16         * 130,131,132,152,155,156,185,186
  19. 17         */
  20. NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
  21. /**
  22. 20         * 中国电信:China Telecom
  23. 21         * 133,1349,153,180,189
  24. 22         */
  25. NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
  26. /**
  27. 25         * 大陆地区固话及小灵通
  28. 26         * 区号:010,020,021,022,023,024,025,027,028,029
  29. 27         * 号码:七位或八位
  30. 28         */
  31. // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
  32. NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
  33. NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
  34. NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
  35. NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
  36. if (([regextestmobile evaluateWithObject:mobileNum] == YES)
  37. || ([regextestcm evaluateWithObject:mobileNum] == YES)
  38. || ([regextestct evaluateWithObject:mobileNum] == YES)
  39. || ([regextestcu evaluateWithObject:mobileNum] == YES))
  40. {
  41. if([regextestcm evaluateWithObject:mobileNum] == YES) {
  42. NSLog(@"China Mobile");
  43. } else if([regextestct evaluateWithObject:mobileNum] == YES) {
  44. NSLog(@"China Telecom");
  45. } else if ([regextestcu evaluateWithObject:mobileNum] == YES) {
  46. NSLog(@"China Unicom");
  47. } else {
  48. NSLog(@"Unknow");
  49. }
  50. return YES;
  51. }
  52. else
  53. {
  54. return NO;
  55. }
  56. }

(6)邮箱验证、电话号码验证:

[cpp] view plaincopy
  1. //是否是有效的正则表达式
  2. +(BOOL)isValidateRegularExpression:(NSString *)strDestination byExpression:(NSString *)strExpression
  3. {
  4. NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", strExpression];
  5. return [predicate evaluateWithObject:strDestination];
  6. }
  7. //验证email
  8. +(BOOL)isValidateEmail:(NSString *)email {
  9. NSString *strRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{1,5}";
  10. BOOL rt = [CommonTools isValidateRegularExpression:email byExpression:strRegex];
  11. return rt;
  12. }
  13. //验证电话号码
  14. +(BOOL)isValidateTelNumber:(NSString *)number {
  15. NSString *strRegex = @"[0-9]{1,20}";
  16. BOOL rt = [CommonTools isValidateRegularExpression:number byExpression:strRegex];
  17. return rt;
  18. }

(7)NSDate进行筛选

[cpp] view plaincopy
  1. //日期在十天之内:
  2. NSDate *endDate = [[NSDate date] retain];
  3. NSTimeInterval timeInterval= [endDate timeIntervalSinceReferenceDate];
  4. timeInterval -=3600*24*10;
  5. NSDate *beginDate = [[NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval] retain];
  6. //对coredata进行筛选(假设有fetchRequest)
  7. NSPredicate *predicate_date =
  8. [NSPredicate predicateWithFormat:@"date >= %@ AND date <= %@", beginDate,endDate];
  9. [fetchRequest setPredicate:predicate_date];
  10. //释放retained的对象
  11. [endDate release];
  12. [beginDate release];

iOS NSPredicate 模糊、精确、查询相关推荐

  1. 字符串模糊/精确查询——mysql

    模糊查询: where 字段 like'%字符串%' 精确查询: where find_in_set('精确字符串',字段名) 转载于:https://www.cnblogs.com/26055490 ...

  2. mongotemplate模糊查_java 中 mongodb的各种操作 模糊查询 精确查询 等等

    本意是想查查mongo数据库的int类型的like怎么查,但是好像没 解决这个问题. 精确查询:模糊查询:分页查询,每页多少:按某个字段排序(或升或降):查询数量:大于,小于,等于:且,或,某个字段不 ...

  3. vc mysql 查询_VC++数据库模糊查询及精确查询示例代码分享

    VC++数据库模糊查询及精确查询示例代码分享是小编为大家带来的一个VC++电话簿程序中的模糊查询例子源代码,结合数据库,可以学习研究下简单一点的模糊查询和精确查询,希望能对大家有帮助,,赶紧来详细了解 ...

  4. Mongotemplate mongodb的各种操作 模糊查询 精确查询

    mongotemplate mongodb的各种操作 模糊查询 精确查询 - 门罗的魔术师 - 博客园

  5. 精确查询和模糊查询,前端往后端传值

    xqbm 的精确查询: if(StringUtils.isNotBlank(params.get("xqbm"))){wrapper.eq(GjWiredNetwork::getX ...

  6. xadmin oracle 查询,Django admin 实现search_fields精确查询实例

    我就废话不多说了,还是直接看代码吧! search_fields = (u'gift_rule_id',u'user_id', u'activity_id',) //默认的查询集合 def get_q ...

  7. mysql模糊连接查询_mysql 模糊查询 concat()

    concat() 函数,是用来连接字符串. 精确查询: select * from user where name="zhangsan" 模糊查询: select * from u ...

  8. 【VBAPlanet】如何实现数据精确查询与匹配

    大家好,我是海林,今天跟大家分享的VBA小代码主题是数据精确查询与匹配. 我们用王者荣耀的数据来举例,如下图所示.根据A:C列的数据源信息,查询E列英雄名相应的职业类型,如果查询无结果,则返回空白. ...

  9. php多关键词精确查找,搜索引擎,全文搜索_请问有没有搜索引擎能做到Like级别的任意关键词精确查询?,搜索引擎,全文搜索,lucene,elasticsearch,百度 - phpStudy...

    请问有没有搜索引擎能做到Like级别的任意关键词精确查询? 举个例子,对于新闻[http://tech.163.com/15/0323/07/ALCIH40U000915BF.html],在正文中,按 ...

最新文章

  1. 云计算架构设计6大原则,你遵循了吗?
  2. LaTex中的documentclass{type}应该填什么
  3. 请使用 WITH MOVE 选项来标识该文件的有效位置。
  4. conda (picard)
  5. ds18b20温度传感器 lcd C语言,C程序控制18B20测温及LCD显示源码打包
  6. 线性表的C/C++实现(数据结构 严蔚敏版)
  7. Spring自定义注解简单使用四步走
  8. mvc identity连接mysql_asp.net MVC5,如何使用mysql数据库,使用MVC框架中自带的identity用户验证体系...
  9. MachineLearning(5)-去量纲:归一化、标准化
  10. 如何重启虚拟机里的ssh服务器,通过SSH重启 vSphere 虚拟机
  11. pandas—pandas.DataFrame.query与pandas.DataFrame.reset_index
  12. cifs mount fail
  13. 软考中级软件设计师考试大纲
  14. QCC小组活动推行知识系列介绍
  15. SPI转can芯片CSM300详解以及Linux驱动移植调试笔记
  16. 使用BootStrap制作网页页面
  17. Spring Cloud Stream初窥
  18. coreldraw x4怎么会蓝屏_cdr点另存为没反应 步骤流程了解了么
  19. mpvue开发微信小程序踩坑笔记
  20. vim 复制、删除多行

热门文章

  1. 华为实验18-OSPF区域认证
  2. php.ini配置文件中文详细解释
  3. html的meta标记大全(转自百度)
  4. 温度传感器LM35实验
  5. android基本功
  6. ThinkPHP5.1批量删除
  7. 元认知是认知的监督体系
  8. 三周年之后 网易游戏和阴阳师都跌落神坛了?
  9. spring mysql ssl_MySQL 使用 SSL 连接配置详解
  10. win32api 中mouse_event、GetFullPathName(fileName)、.GetLocalTime()、GetSystemDirectory()等函数的用法