简述: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. 使用FileUpload控件上传图片并自动生成缩略图、自动生成带文字和图片的水印图
  2. 刚刚,arXiv论文数破200万!没有arXiv,就没有21世纪的科研突破
  3. [M]MagicTable转换异常解决方法
  4. 重磅解读 | 赵义博:量子密码的绝对安全只存在于理论
  5. Java使用HTTPClient4.3开发的公众平台消息模板的推送功能
  6. 使用和执行SQL Server Integration Services包的方法
  7. 进退两难的硅谷程序员们
  8. POJ1741 点分治模板
  9. js:toastr弹出提示信息
  10. Python爬虫入门教程第七讲: 蜂鸟网图片爬取之二
  11. 千锋php 靠谱吗,千锋PHP学员心得 长久的坚持不懈才能接近成功
  12. 我有一壶酒,足以慰风尘
  13. 我是鉴黄师,在工作中遇到了我的前女友……
  14. Android性能优化系列之Bitmap图片优化
  15. 跟锦数学2017年02月
  16. pdf大小如何压缩?
  17. 电气成套设备远程监控应用
  18. 《第一行代码》学习笔记——第1章 开始启程,你的第一行Android代码
  19. js添加、删除DOM元素
  20. 这个必用的开发框架,是多少程序员头秃的存在?

热门文章

  1. 中企故事汇:铁匠之乡借东风出海
  2. 小学文化学导数——斜率
  3. 同样协调个事情,为什么有人一说就通,有人一说就炸?(转,知乎)
  4. 环境工程原理复习资料
  5. 【科普贴】LDO电源详解
  6. 全球卫星导航系统(GNSS)频率表(2017年)
  7. RINEX2.10、2.11 : (观测值文件)不同观测值类型对比
  8. 迅雷和小米这对好基友,究竟在密谋什么?
  9. 导航电子地图数据中POI搜索技术原理之二
  10. Epoll触发事件的类型(转载)