您的位置:首页 > 移动开发 > IOS开发

IOS 正则和NSPredicate使用样例

2014-03-11 15:02 288 查看
-(NSDictionary*)urlDic:(NSString*)urlString { NSString*regex=@"([^?=&]+)(=([^&]*))"; NSRegularExpression*numberRegex=[[NSRegularExpressionalloc]initWithPattern:regexoptions:NSRegularExpressionCaseInsensitiveerror:nil]; NSArray*parmMatchs=[numberRegexmatchesInString:urlStringoptions:0range:NSMakeRange(0,urlString.length)]; NSMutableDictionary*dic=[NSMutableDictionarydictionary]; for(NSString*stringinparmMatchs){ NSArray*array=[stringcomponentsSeparatedByString:@"="]; [dicsetObject:array[1]forKey:array[0]]; } returndic; }

-(NSString*)pasretel:(NSString*)urlString{ NSString*regex=@"\\d"; NSRegularExpression*numberRegex=[[NSRegularExpressionalloc]initWithPattern:regexoptions:NSRegularExpressionCaseInsensitiveerror:nil]; NSArray*parmMatchs=[numberRegexmatchesInString:urlStringoptions:0range:NSMakeRange(0,urlString.length)]; NSMutableString*str=[[NSMutableStringalloc]init]; for(NSTextCheckingResult*matchinparmMatchs){ NSRangematchRange=match.range; [strappendString:[NSStringstringWithFormat:@"%@",[urlStringsubstringWithRange:matchRange]]]; } returnstr; }

 

-(NSArray*)getOnlyNum:(NSString*)str
{

  NSString*onlyNumStr=[strstringByReplacingOccurrencesOfString:@"[^0-9,]"withString:@""options:NSRegularExpressionSearchrange:NSMakeRange(0,[strlength])];
  NSArray*numArr=[onlyNumStrcomponentsSeparatedByString:@","];
  returnnumArr;
}

testStr*str=[[testStralloc]init];
NSString*testStr=@"111111(哈哈),22222222222<各个>,3333333333[订单],44444444";
NSLog(@"结果为:%@",[strgetOnlyNum:testStr]);

输出结果:
  2013-05-1414:54:00.306test[3559:303]结果为:(
    111111,
    22222222222,
    3333333333,
  )

 

NSPredicate最常用到的函数

+(NSPredicate*)predicateWithFormat:(NSString*)predicateFormat,...;


1.比较运算符>、<、==、>=、<=、!=
例:@"number>=99"

2.范围运算符:IN、BETWEEN
例:@"numberBETWEEN{1,5}"
@"addressIN{'shanghai','nanjing'}"

3.字符串本身:SELF
例:@"SELF=='APPLE'"

4.字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
例:@"nameCONTAIN[cd]'ang'"//包含某个字符串
@"nameBEGINSWITH[c]'sh'"//以某个字符串开头
@"nameENDSWITH[d]'ang'"//以某个字符串结束
注:[c]不区分大小写,[d]不区分发音符号即没有重音符号,[cd]既不区分大小写,也不区分发音符号。

5.通配符:LIKE
例:@"nameLIKE[cd]'*er*'"//*代表通配符,Like也接受[cd].
@"nameLIKE[cd]'???er*'"

6.正则表达式:MATCHES
例:NSString*regex=@"^A.+e$";//以A开头,e结尾
@"nameMATCHES%@",regex

实际应用:对NSArray进行过滤

NSArray*array=[[NSArrayalloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan",nil];
NSString*string=@"ang";
NSPredicate*pred=[NSPredicatepredicateWithFormat:@"SELFCONTAINS%@",string];
NSLog(@"%@",[arrayfilteredArrayUsingPredicate:pred]);


实际应用:判断字符串首字母是否为字母

NSString*regex=@"[A-Za-z]+";
NSPredicate*predicate=[NSPredicatepredicateWithFormat:@"SELFMATCHES%@",regex];

if([predicateevaluateWithObject:aString]){
}


实际应用:字符串替换

NSError*error=NULL;
NSRegularExpression*regex=[NSRegularExpressionregularExpressionWithPattern:@"(encoding=\")[^\"]+(\")"
options:0
error:&error];
NSString*sample=@"<xmlencoding=\"abc\"></xml><xmlencoding=\"def\"></xml><xmlencoding=\"ttt\"></xml>";
NSLog(@"Start:%@",sample);
NSString*result=[regexstringByReplacingMatchesInString:sample
options:0
range:NSMakeRange(0,sample.length)
withTemplate:@"$1utf-8$2"];
NSLog(@"Result:%@",result);


实际应用:判断手机号码,电话号码函数

//正则判断手机号码地址格式
-(BOOL)isMobileNumber:(NSString*)mobileNum
{
/**
*手机号码
*移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
*联通:130,131,132,152,155,156,185,186
*电信:133,1349,153,180,189
*/
NSString*MOBILE=@"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
/**
10*中国移动:ChinaMobile
11*134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
12*/
NSString*CM=@"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
/**
15*中国联通:ChinaUnicom
16*130,131,132,152,155,156,185,186
17*/
NSString*CU=@"^1(3[0-2]|5[256]|8[56])\\d{8}$";
/**
20*中国电信:ChinaTelecom
21*133,1349,153,180,189
22*/
NSString*CT=@"^1((33|53|8[09])[0-9]|349)\\d{7}$";
/**
25*大陆地区固话及小灵通
26*区号:010,020,021,022,023,024,025,027,028,029
27*号码:七位或八位
28*/
//NSString*PHS=@"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";

NSPredicate*regextestmobile=[NSPredicatepredicateWithFormat:@"SELFMATCHES%@",MOBILE];
NSPredicate*regextestcm=[NSPredicatepredicateWithFormat:@"SELFMATCHES%@",CM];
NSPredicate*regextestcu=[NSPredicatepredicateWithFormat:@"SELFMATCHES%@",CU];
NSPredicate*regextestct=[NSPredicatepredicateWithFormat:@"SELFMATCHES%@",CT];

if(([regextestmobileevaluateWithObject:mobileNum]==YES)
||([regextestcmevaluateWithObject:mobileNum]==YES)
||([regextestctevaluateWithObject:mobileNum]==YES)
||([regextestcuevaluateWithObject:mobileNum]==YES))
{
if([regextestcmevaluateWithObject:mobileNum]==YES){
NSLog(@"ChinaMobile");
}elseif([regextestctevaluateWithObject:mobileNum]==YES){
NSLog(@"ChinaTelecom");
}elseif([regextestcuevaluateWithObject:mobileNum]==YES){
NSLog(@"ChinaUnicom");
}else{
NSLog(@"Unknow");
}

returnYES;
}
else
{
returnNO;
}
}

实际应用:NSDate进行筛选

//日期在十天之内:
NSDate*endDate=[[NSDatedate]retain];
NSTimeIntervaltimeInterval=[endDatetimeIntervalSinceReferenceDate];
timeInterval-=3600*24*10;
NSDate*beginDate=[[NSDatedateWithTimeIntervalSinceReferenceDate:timeInterval]retain];
//对coredata进行筛选(假设有fetchRequest)
NSPredicate*predicate_date=
[NSPredicatepredicateWithFormat:@"date>=%@ANDdate<=%@",beginDate,endDate];

[fetchRequestsetPredicate:predicate_date];
//释放retained的对象
[endDaterelease];
[beginDaterelease];



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: