[Depth study iOS development (d)] Regular Expression (regex)

Regular Expression (regex)

 

Wikipedia: http://en.wikipedia.org/wiki/Regular_expression

Online test regular expressions: http://tool.chinaz.com/regex/

 

Regular expressions, often used for file searching and data validation, etc.

iOS provides support for regular expressions: NSRegularExpression

 

Code Example:

- (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];
}

 

 

Reproduced in: https: //www.cnblogs.com/dyingbleed/archive/2013/05/17/3036113.html

Guess you like

Origin blog.csdn.net/weixin_33923148/article/details/93301872