iOS中的过滤器和正则表达式(NSPredicate,NSRegularExpression)
参考链接:http://www.cocoachina.com/industry/20140321/8024.html
NSPredicate
Cocoa提供了一个NSPredicate类,它用来指定过滤器的条件
初始化方法
+ (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...;
Format:
/**
1.格式说明符
%d和%@等插入数值和字符串,%K表示key
还可以引入变量名,用$,类似环境变量,如:@"name == $NAME",再用predicateWithSubstitutionVariables调用来构造新的谓词(键/值字典),其中键是变量名,值是要插入的内容,注意这种情况下不能把变量当成键路径,只能用作值
2.运算符
==等于
>:大于
>=和=>:大于或等于
<:小于
<=和=<:小于或等于
!=和<>:不等于
括号和逻辑运算AND、OR、NOT或者C样式的等效表达式&&、||、!
注意:不等号适用于数字和字符串
3. 数组运算符
BETWEEN和IN后加某个数组,可以用{50,200},也可以用%@格式说明符插入自己的对象,也可以用变量
4.SELF足够了
self就表示对象本身
5.字符串运算符
BEGINSWITH:以某个字符串开头
ENDSWITH:以某个字符串结束
CONTAINS:包含某个字符串
@"name ENDSWITH[d] 'ang'"
[c],[d],[cd],后缀表示不区分大小写,不区分发音符号,两这个都不区分 6.LIKE运算符
类似SQL的LIKES
LIKE,与通配符“*”表示任意多和“?”表示一个结合使用
LIKE也接受[cd]符号
7.MATCHES可以使用正则表达式
NSString *regex = @"^A.+e$"; //以A开头,e结尾
*/
数组的类目:用来过滤数组
- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate;
可变数组可以直接过滤
- (void)filterUsingPredicate:(NSPredicate *)predicate;
例:过滤出数组中的字符串中含有ang的元素
NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];
NSString *string = @"ang";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",string];
NSLog(@"%@",[array filteredArrayUsingPredicate:pred]);
单个对象的过滤
- (BOOL)evaluateWithObject:(id)object;
例:判断字符串中首字母是不是字母
NSString *regex = @"[A-Za-z]+";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([predicate evaluateWithObject:@"hahaa"]) {
NSLog(@"首字母含有字母");
}else {
NSLog(@"首字母不含字母");
}
过滤语句:邮箱过滤@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{1,5}";
电话号码部分:@"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$"
NSRegularExpression
字符串替换
NSError* error = NULL;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"(encoding=\")[^\"]+(\")"
options:
error:&error];
NSString* sample = @"<xml encoding=\"abc\"></xml><xml encoding=\"def\"></xml><xml encoding=\"ttt\"></xml>";
NSLog(@"Start:%@",sample);
NSString* result = [regex stringByReplacingMatchesInString:sample
options:
range:NSMakeRange(, sample.length)
withTemplate:@"$1utf-8$2"];
NSLog(@"Result:%@", result);
字符串中截取字符串
//组装一个字符串,需要把里面的网址解析出来
NSString *urlString=@"<meta/><link/><title>1Q84 BOOK1</title></head><body>";
//NSRegularExpression类里面调用表达的方法需要传递一个NSError的参数。下面定义一个
NSError *error;
//http+:[^\\s]* 这个表达式是检测一个网址的。(?<=title\>).*(?=</title)截取html文章中的<title></title>中内文字的正则表达式
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=title\\>).*(?=</title)" options: error:&error];
if (regex != nil) {
NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options: range:NSMakeRange(, [urlString length])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:];
//从urlString当中截取数据
NSString *result=[urlString substringWithRange:resultRange];
//输出结果
NSLog(@"->%@<-",result);
}
}
NSPredicate测试:
其中自定义一个类,出事的时候给属性赋值,用runtime获取所有属性并重写description方法
@interface DataModel : NSObject @property (nonatomic,copy)NSString *name;
@property (nonatomic,assign)NSInteger num; @end
#import "DataModel.h"
#import <objc/runtime.h> @implementation DataModel - (instancetype)init
{
self = [super init];
if (self) {
self.name = @"haha";
self.num = ;
}
return self;
} //修改描述文件(获取所有属性存成字典)
- (NSString *)description {
u_int count;
objc_property_t* properties= class_copyPropertyList([self class], &count);
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for (int i = ; i < count ; i++)
{
const char* propertyName = property_getName(properties[i]);
NSString *strName = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
[dic setObject:[self valueForKey:strName] forKey:strName];
}
return [NSString stringWithFormat:@"<%@ %p>:%@",self.class,&self,dic];
}
例子:
//(1)比较运算符>,<,==,>=,<=,!=
- (void)test1 {
DataModel *model = [[DataModel alloc]init];
//类里面
/*
self.name = @"haha";
self.num = 12;
*/
//可判定一个类的一个属性是否等于某个值,字符串是否相等
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"num > 11"];
BOOL match = [predicate evaluateWithObject:model];
NSLog(@"%@",match?@"yes":@"no");
} //强悍的数组过滤功能
- (void)test2 {
NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
DataModel *model1= [[DataModel alloc]init];
DataModel *model2 = [[DataModel alloc]init];
DataModel *model3 = [[DataModel alloc]init];
model2.num = ;
model3.name = @"lala";
[mutableArray addObject:model1];
[mutableArray addObject:model2];
[mutableArray addObject:model3];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"num > 10 AND name == 'lala'"];
[mutableArray filterUsingPredicate:predicate];
NSLog(@"过滤出了: %@",mutableArray);
} //含有变量的谓词,在这里用><会崩溃
- (void)test3 {
DataModel *model= [[DataModel alloc]init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == $key"];
NSDictionary *dic = @{@"key":@"haha"};
NSPredicate *predicate1 = [predicate predicateWithSubstitutionVariables:dic];
NSLog(@"%@",predicate1);
BOOL match = [predicate1 evaluateWithObject:model];
NSLog(@"%@",match?@"yes":@"no");
} //BETWEEN
//BETWEEN和IN后加某个数组,可以用{50,200},也可以用%@格式说明符插入自己的对象,也可以用变量
- (void)test4 {
NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
DataModel *model1= [[DataModel alloc]init];
DataModel *model2 = [[DataModel alloc]init];
DataModel *model3 = [[DataModel alloc]init];
model2.num = ;
model3.num = ;
[mutableArray addObject:model1];
[mutableArray addObject:model2];
[mutableArray addObject:model3];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"num BETWEEN {5,15}"];
[mutableArray filterUsingPredicate:predicate];
NSLog(@"过滤出了: %@",mutableArray);
} //IN运算符 - (void)test5 {
NSArray *arrayFilter = [NSArray arrayWithObjects:@"abc1", @"abc2", nil];
NSMutableArray *arrayContent = [NSMutableArray arrayWithObjects:@"a1", @"abc1", @"abc4", @"abc2", nil];
//过滤出arrayContent 不包含 arrayFilter的元素
NSPredicate *thePredicate = [NSPredicate predicateWithFormat:@"NOT (SELF in %@)", arrayFilter];
[arrayContent filterUsingPredicate:thePredicate];
NSLog(@"%@",arrayContent);
} //BEGINSWITH,ENDSWITH,CONTAINS
//LIKE运算符(通配符)
- (void)test6 {
NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
DataModel *model1= [[DataModel alloc]init];
DataModel *model2= [[DataModel alloc]init];
DataModel *model3= [[DataModel alloc]init];
model1.name = @"a123.png";
model3.name = @"a.png";
[mutableArray addObject:model1];
[mutableArray addObject:model2];
[mutableArray addObject:model3];
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] 'a*.png'"];
[mutableArray filterUsingPredicate:predicate];
NSLog (@"%@", mutableArray);
}
iOS中的过滤器和正则表达式(NSPredicate,NSRegularExpression)的更多相关文章
- 【原/转】iOS中非常强大的过滤器:NSPredicate
		
在APPLE的官方Demo:UICatalog中实现UISearchBar模糊搜索功能是这么做的: - (void)viewDidLoad { [super viewDidLoad]; self.al ...
 - iOS中运用正则表达式
		
iOS中运用正则表达式来匹配短信验证码,电话号码,邮箱等是比较常见的. 在iOS中运用正则表达式主要有三种方式: -:通过谓词下面是实例代码: - (BOOL)regularExpresionWith ...
 - 正则表达式在iOS中的运用
		
1.什么是正则表达式 正则表达式,又称正规表示法,是对字符串操作的一种逻辑公式.正则表达式可以检测给定的字符串是否符合我们定义的逻辑,也可以从字符串中获取我们想要的特定部分.它可以迅速地用极简单的方式 ...
 - iOS中使用正则
		
一.什么是正则表达式 正则表达式,又称正规表示法,是对字符串操作的一种逻辑公式.正则表达式可以检测给定的字符串是否符合我们定义的逻辑,也可以从字符串中获取我们想要的特定部分.它可以迅速地用极简单的方式 ...
 - iOS开发之详解正则表达式
		
本文由Charles翻自raywenderlich原文:NSRegularExpression Tutorial: Getting Started更新提示:本教程被James Frost更新到了iOS ...
 - iOS中的数据持久化方式
		
iOS中的数据持久化方式,基本上有以下四种:属性列表.对象归档.SQLite3和Core Data. 1.属性列表 涉及到的主要类:NSUserDefaults,一般 [NSUserDefaults ...
 - 关于ios中的文本操作-简介
		
来源:About Text Handling in iOS 官方文档 iOS平台为我们提供了许多在app中展示文本和让用户编辑文本的方式.同时,它也允许你在app视图中展示格式化的文本和网页内容.你可 ...
 - iOS中常用的四种数据持久化技术
		
iOS中的数据持久化方式,基本上有以下四种:属性列表 对象归档 SQLite3和Core Data 1.属性列表涉及到的主要类:NSUserDefaults,一般 [NSUserDefaults st ...
 - iOS中常用的四种数据持久化方法简介
		
iOS中常用的四种数据持久化方法简介 iOS中的数据持久化方式,基本上有以下四种:属性列表.对象归档.SQLite3和Core Data 1.属性列表涉及到的主要类:NSUserDefaults,一般 ...
 
随机推荐
- 自定义消息中如果需要定义WPARAM和LPARAM,该怎么使用和分配?
			
写Windows程序不可避免要使用自定义的消息,也就是从WM_USER开始定义的消息.在定义一个消息后,往往我们还要定义针对该消息的WPARAM甚至是LPARAM.WPARAM和LPARAM是什么,可 ...
 - 10个优秀的移动Web应用开发框架
			
在最近几年里,移动互联网高速发展.市场潜力巨大.继计算机.互联网之后,移动互联网正掀起第三次信息技术革命的浪潮,新技术.新应用不断涌现.今天这篇文章向大家推荐10大优秀的移动Web开发框架,帮助开发者 ...
 - 添加 SSH 公钥
			
生成 SSH 密钥 ssh-keygen -t rsa -C "YOUR_EMAIL@YOUREMAIL.COM" 获取 SSH 公钥信息 cat ~/.ssh/id_rsa.pu ...
 - JS中的事件、事件冒泡和事件捕获、事件委托
			
https://www.cnblogs.com/diver-blogs/p/5649270.html https://www.cnblogs.com/Chen-XiaoJun/p/6210987.ht ...
 - CPP-基础:C++的new int()与new int[]
			
编写一个List类: class List { int length; //列表长度 int* lpInt; //列表指针 List(int size); ~List(); } List::List( ...
 - shell脚本,计算1+3+5....100等于多少?
			
[root@localhost wyb]# cat unevenjia.sh #!/bin/bash #从1+++...100的结果 i= count=$1 $count` do sum=$(($su ...
 - javase(8)_集合框架_List、Set、Map
			
一.集合体系(不包括Queue体系) 二.ArrayList ArrayList的属性 private transient Object[] elementData; //存储元素 private i ...
 - 移动产品设计之ios系统的导航
			
做道题:[不定项选择题] OS中导航设计模式有几种? A.平铺导航 B.标签导航 C.树形导航 D.模态视图导航 正确答案:A B C 讲解: 导航始终是产品设计的重头戏,往往产品设计中90%的事情就 ...
 - javascipt的forEach
			
1.Array let arr = [1, 2, 3]; arr.forEach(function (element, index, array) { console.log('数组中每个元素:', ...
 - [LUOGU] 1892 团伙
			
题目描述 1920年的芝加哥,出现了一群强盗.如果两个强盗遇上了,那么他们要么是朋友,要么是敌人.而且有一点是肯定的,就是: 我朋友的朋友是我的朋友: 我敌人的敌人也是我的朋友. 两个强盗是同一团伙的 ...