简述: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];

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],在正文中,按 ...

  10. Excel 中使用SQL 语句查询数据(七)-----用LIKE 运算符进行模糊匹配查询

    这篇博文要和大家分享的是用LIKE 运算符进行模糊匹配查询下图数据源商品代号包含数字的数据. 我们用Microsoft query连接数据源,步骤请参考本系列第一篇博文.语句如下图 其中 LIKE ' ...

最新文章

  1. 你不可不知的9种Lisp语言思想
  2. cnblogs反对按钮点击测试
  3. python编码类型互转总结
  4. linux终端中如何对目录压缩,软网推荐:Linux中使用命令行查看压缩文档
  5. OpenCV霍夫变换的演示代码(附完整代码)
  6. 返回值被忽略_《Jenkins Tips 001》 忽略 Shell 步骤中的故障
  7. java炫舞_Java 炫舞按键功能 DancingPlay (整理)
  8. 数据结构--Go 语言中 Set 的最佳实现方案
  9. 使用 Microsoft.UI.Xaml 解决 UWP 控件和对老版本 Windows 10 的兼容性问题
  10. 小宇飞刀与xieyunc
  11. golang Windows下编译linux可执行文件
  12. SAP BW常用后台事务码
  13. 驾考 曲线行驶 s弯
  14. 网站漏洞修复之UEditor漏洞 任意文件上传漏洞
  15. 在Xubuntu上安装中文输入法
  16. 股票指标php源码,【图】成功率98.7%超高成功率指标(源码 有图 无未来)_炒股,炒股公式,股票论坛,炒股软件,股票指标_指标公式分享交流论坛_理想论坛 - 股票论坛...
  17. 到底什么是UI设计规范
  18. 工欲善其事必先利其器–SimpleTestBed
  19. 算法开启队列转栈武魂
  20. 如何命名计算机快捷键,重命名的快捷键,教您重命名的快捷键是什么

热门文章

  1. Matlab 斜率和曲率,曲率_与闪电共舞_新浪博客
  2. 计算机网络测试仪,网络测试仪如何使用
  3. 狸猫浏览器v2.0功能解析
  4. The Pilots Brothers‘ refrigerator(思维)
  5. 网页设计:Meta标签详解
  6. 常见模块设计--权限管理(一)
  7. mysql是串行还是并行的_sql执行的作业是串行还是并行的?
  8. 花老湿学习OpenCV:霍夫线变换与直线检测
  9. Linux环境下查看日志文件命令详解
  10. CSP 2021 复赛游记