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,一般 ...
随机推荐
- Visual SVN IIS反向代理设置
需要解决的问题: 1. 设置反向代理 2. 解决部分后缀文件无法提交的问题 1. 设置反向代理 接收所有的URL 允许所有的HTTP_HOST 跳转到被代理的服务器 2. 允许所有后缀的文件访问IIS ...
- php类重载
首先,因为PHP是弱类型语言,是不直接支持重载的,不过可以通过一些方法来实现重载. 先说一下重写 在子类继承父类方法后,自己重新定义父类的方法,包含函数名,形参(个数,顺序)完全相同,但权限修饰符可不 ...
- LR中订单流程脚本
Action(){ /* 主流程:登录->下订单->支付订单->获取订单列表 定义事物 1)登录 2)下订单 3)支付订单 4)获取订单列表 接口为:application/json ...
- tomcat 发布本地文件
应用场景,通过web,jsp访问本地mouse文件夹的静态文件 通过修改tomcat配置文件server.xml <!--在Host标签下加入Context标签,path指的是服务器url请求地 ...
- codeforces 121 E. Lucky Array
time limit per test 4 seconds memory limit per test 256 megabytes input standard input output standa ...
- C语言指针系列 - 一级指针.一维数组,二级指针,二维数组,指针数组,数组指针,函数指针,指针函数
1. 数组名 C语言中的数组名是一个特殊的存在, 从本质上来讲, 数组名是一个地址, 我们可以打印一个指针的值,和打印一个数组的值来观察出这个本质: int nArray[10] ={ 0 }; in ...
- mvc的model验证,ajaxhelper,验证机制语法
ajaxhelper: onsuccess是调用成功后显示方法,还有一个方法是调用前显示 model验证: 控件前端验证: 需要引入的JS 其中第二个是ajaxhelper的必须验证 后台的两个同名不 ...
- 7.逻辑运算 and or not
1)优先级 ()> not > and > o r and:真真为真,真假为假 ,假假为假 or:真真为真,真假为真,假假为假 print(2 > 1 and 1 < ...
- http post get 同步异步
下面首先介绍一下一些基本的概念---同步请求,异步请求,GET请求,POST请求. 1.同步请求从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作.也 ...
- MySQLfailover错误一则
由于公司现有主库要转移到新的主库上,所以,我打算利用MySQLfailover工具的故障转移. 1.开发把程序账号转移到新主库上 2.停止现有主库,使之进行故障转移,转移期间会自动锁表,保持数据一致性 ...