【深入学习iOS开发(四)】Regular Expression(正则表达式)

Regular Expression(正则表达式)

 

维基百科:http://en.wikipedia.org/wiki/Regular_expression

正则表达式在线测试:http://tool.chinaz.com/regex/

 

正则表达式,常用于文件搜索和数据校验等

iOS 提供了对正则表达式的支持:NSRegularExpression

 

代码示例:

- (BOOL)isValidWithRegex:(NSString *) regex {
    BOOL result = NO;
    
    if (regex != nil) {
        NSError *error = nil;
        NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regex options:0 error:&error];
        NSRange range = [regularExpression rangeOfFirstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
        if (range.location != NSNotFound) {
            result = YES;
        }
    }
    
    return result;
}

- (BOOL)isValidChineseName {
    static NSString *chineseNameRegex = @"^[\\u4e00-\\u9fa5]{2,4}$";
    return [self isValidWithRegex:chineseNameRegex];
}

- (BOOL)isValidPhoneNumber {
    static NSString *phoneNumberRegex = @"^\\d{11}|((\\d{3,4}-)?\\d{7,8})$";
    return [self isValidWithRegex:phoneNumberRegex];
}

 

 

posted on 2013-05-17 17:04  Anthony Li  阅读(1835)  评论(0编辑  收藏  举报

博客园博客已停止更新,博客地址:dyinigbleed.com