iOS三种正则表达式

1.利用NSPredicate(谓词)匹配 
例如匹配有效邮箱: 

1 NSString *email = @“nijino_saki@163.com”; 
2 NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
3 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; 
4 BOOL isValid = [predicate evaluateWithObject:email];

谓词匹配比较灵活,但是需要有谓词的相关知识。 

2.利用rangeOfString:option:直接查找 

1 NSString *searchText = @"// Do any additional setup after loading the view, typically from a nib."; 
2 
3 NSRange range = [searchText rangeOfString:@"(?:[^,])*\\." options:NSRegularExpressionSearch]; 
4 
5 if (range.location != NSNotFound) { 
6     NSLog(@"%@", [searchText substringWithRange:range]); 
7 }

options中设定NSRegularExpressionSearch就是表示利用正则表达式匹配,会返回第一个匹配结果的位置。 

3.使用正则表达式类 

1 NSString *searchText = @"// Do any additional setup after loading the view, typically from a nib.";    
2 NSError *error = NULL;
3 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?:[^,])*\\." options:NSRegularExpressionCaseInsensitive error:&error];
4 NSTextCheckingResult *result = [regex firstMatchInString:searchText options:0 range:NSMakeRange(0, [searchText length])];
5 if (result) {
6     NSLog(@"%@\n", [searchText substringWithRange:result.range]);
7 }

使用系统的正则表达式类(NSRegularExpression)会返回匹配的多个结果。

posted @ 2016-12-21 15:28 勇猛的小黑 阅读(...) 评论(...) 编辑 收藏