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,一般 ...
随机推荐
- 从零开始利用vue-cli搭建简单音乐网站(五)
上一篇文章讲到的是如何利用mongoose从数据库读取数据然后更新页面,接下来要实现的就是用户注册登录功能,这个功能涉及到的东西太多了,今天只实现了登录功能,登陆之后更新导航条界面,最后效果如下: 登 ...
- JS常用的技术
思考与总结 1.模块化 曾看到某大牛说:模块化和组件化是前端开发的一大趋势.所谓的模块化一般是指为了实现一个特定的功能而将所有的代码(对象)封装成一个模块.而AMD就是requireJS为指定模块规范 ...
- nagios的一些东西
make install 用来安装nagios的主程序,cgi和html文件 make install-init 在/etc/rc.d/init.d目录下创建nagios启动脚本 make insta ...
- codevs 1115 开心的金明
时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold 题目描述 Description 金明今天很开心,家里购置的新房就要领钥匙了,新房里有一间他自己专用的很宽敞的房 ...
- haml scss转换编写html css的前期工作
http://www.w3cplus.com/sassguide/install.html 先下载ruby $ gem sources $ gem sources --remove https://r ...
- leecode 旋转数组
描述 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数. 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋 ...
- iOS上架问题解决
dns问题 http://iphone.91.com/tutorial/syjc/140509/21686339.html 网络问题 手机4g开wifi,上传提交多次 时间问题 东八区下午6点上架成功 ...
- wxwidgets编译及环境配置
wxwidgets编译及环境配置 安装步骤: 到www.CodeBlocks.org下载并安装CodeBlocks,最好下载MinGW版本的,可以省掉安装和配置GCC的麻烦. 到www.wxWidge ...
- keras中的shape/input_shape
在keras中,数据是以张量的形式表示的,张量的形状称之为shape,表示从最外层向量逐步到达最底层向量的降维解包过程.“维”的也叫“阶”,形状指的是维度数和每维的大小.比如,一个一阶的张量[1,2, ...
- Codeforces Round #271 (Div. 2)-A. Keyboard
http://codeforces.com/problemset/problem/474/A A. Keyboard time limit per test 2 seconds memory limi ...