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结尾
*/
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]);
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(@"首字母不含字母");
}
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:0
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:0
range:NSMakeRange(0, sample.length)
withTemplate:@"$1utf-8$2"];
NSLog(@"Result:%@", result);
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"(encoding=\")[^\"]+(\")"
options:0
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:0
range:NSMakeRange(0, 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:0 error:&error];
if (regex != nil) {
NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];
//从urlString当中截取数据
NSString *result=[urlString substringWithRange:resultRange];
//输出结果
NSLog(@"->%@<-",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:0 error:&error];
if (regex != nil) {
NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];
//从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
@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 = 12;
}
return self;
}
//修改描述文件(获取所有属性存成字典)
- (NSString *)description {
u_int count;
objc_property_t* properties= class_copyPropertyList([self class], &count);
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for (int i = 0; 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];
}
#import <objc/runtime.h>
@implementation DataModel
- (instancetype)init
{
self = [super init];
if (self) {
self.name = @"haha";
self.num = 12;
}
return self;
}
//修改描述文件(获取所有属性存成字典)
- (NSString *)description {
u_int count;
objc_property_t* properties= class_copyPropertyList([self class], &count);
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for (int i = 0; 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 = 8;
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 = 8;
model3.num = 20;
[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);
}
- (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 = 8;
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 = 8;
model3.num = 20;
[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);
}