【深入学习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];
}

转载于:https://www.cnblogs.com/dyingbleed/archive/2013/05/17/3036113.html

猜你喜欢

转载自blog.csdn.net/weixin_33923148/article/details/93301872