iOS中3种正则表达式的使用与比较

时间:2022-11-11 15:20:32

iOS中有三种方式来实现正则表达式的匹配。现在将他们都记录在这里: 
1.利用NSPredicate(谓词)匹配 

例如匹配有效邮箱: 

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

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

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

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


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

3.使用正则表达式类 

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


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

小结: 
第一种匹配需要学习NSPredicate的写法,需要查阅苹果相关技术文档;如果只关心第一个匹配的结果,第二种匹配较为简洁;如果需要匹配多个结果,同时匹配多次,第三种方式效率会更高