iOS中有三種方式來(lái)實(shí)現(xiàn)正則表達(dá)式的匹配『侔悖現(xiàn)在將他們都記錄在這里:
1.利用NSPredicate(謂詞)匹配
例如匹配有效郵箱:
NSString *email = @"admin@ruanman.net"梅肤;
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];
謂詞匹配比較靈活,但是需要有謂詞的相關(guān)知識(shí)式散。
2.利用rangeOfString:option:直接查找
NSString*searchText =@"http:// Do any additional setup after loading the view, typically from a nib.";
NSRangerange = [searchText rangeOfString:@"(?:[^,])*\\."options:NSRegularExpressionSearch];
if(range.location! = NSNotFound) {
NSLog(@"%@", [searchText substringWithRange:range]);
}
options中設(shè)定NSRegularExpressionSearch就是表示利用正則表達(dá)式匹配汉匙,會(huì)返回第一個(gè)匹配結(jié)果的位置涤姊。
3.使用正則表達(dá)式類
使用系統(tǒng)的正則表達(dá)式類(NSRegularExpression)會(huì)返回匹配的多個(gè)結(jié)果镣衡。
NSString*searchText = @"http:// Do any additional setup after loading the view, typically from a nib.";
NSError*error = NULL;
NSRegularExpression*regex = [NSRegularExpressionregularExpressionWithPattern:@"(?:[^,])*\\."options:NSRegularExpressionCaseInsensitiveerror:&error];
NSTextCheckingResult*result= [regex firstMatchInString:searchText options:0range:NSMakeRange(0, [searchText length])];
if(result) {
NSLog(@"%@\n", [searchText substringWithRange:result.range]);
}