加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式和谓词

发布时间:2020-12-14 00:54:06 所属栏目:百科 来源:网络整理
导读:正则表达式 需要匹配的字符串 str 匹配规则 pattern 正则表达式 NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options: 0 error : nil ]; 匹配结果 NSArray *resultarray= [regularExpression matc

正则表达式

  • 需要匹配的字符串 str
  • 匹配规则 pattern
  • 正则表达式
NSRegularExpression *regularExpression = [NSRegularExpression  regularExpressionWithPattern:pattern options:0 error:nil];
  • 匹配结果
NSArray *resultarray= [regularExpression matchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0,str.length)];

谓词

  • 作用: 判断条件表达式的求值返回真或假的过程
  • 使用步骤:

    • 定义NSPredicate对象并制定条件
    • 调用谓词的evaluateWithObject方法判断指定条件是否满足
  • 条件指令:

    • BEGANWITH 以指定字符开始
    • ENDSWITH 以指定字符结束
    • CONTAINS 包含指定字符
  • 提示:
    • 为此中的匹配指令关键字通常使用大写字母
    • 谓词中可以使用格式字符串
    • 如果通过key path指定匹配条件,需要使用%K

应用1
创建一个数组,里面有50个随机数字
目标: 在数组中,找到包含数字’8’的数字

// self表示数组中的每一项
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self CONTAINS '8'"];

NSArray *result = [arrayM filteredArrayUsingPredicate: predicate];

NSLog(@"%@",result);

这样获取的结果都是包含数字8的元素

应用2
在Person数组中有50个Person对象(三个属性: name/title/age),
需求: 搜索数组中名字有’lisi’ & title 是’boss’

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS 'lisi' AND title CONTAINS 'boss'"]; NSArray *result = [arrayM filteredArrayUsingPredicate: predicate]; NSLog(@"%@",result);

需求: 搜索数组中名字有’lisi’ & title 是’boss’ 或者年龄小于30的人

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(name CONTAINS 'lisi' AND title CONTAINS 'boss') OR age < 30"]; NSArray *result = [arrayM filteredArrayUsingPredicate: predicate]; NSLog(@"%@",result);

注意:

1> 如果利用参数传递字符串,不需要”

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS 'lisi' AND title CONTAINS %@",@"xiami"];

2> 如果要传递属性名(KVC),格式字符串中,需要使用%K

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K CONTAINS 'lisi' AND title CONTAINS %@",@"name",@"xiami"];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读