cocoa中的NSPredicate介紹

      在COCOA中的NSPredicate表示的就是一種判斷。一種條件的構建。咱們能夠先經過NSPredicate中的predicateWithFormat方法來生成一個NSPredicate對象表示一個條件,而後在別的對象中經過evaluateWithObject方法來進行判斷,返回一個布爾值。正則表達式

      廢話很少說,直接上代碼:lua

- (BOOL)validatePhoneNumber
{
    // 手機號以13, 15,18開頭,八個 \d 數字字符
    NSString *phoneNumberRegEx = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$"; 
    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumberRegEx];
    BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]];
    return isCorrect ? YES : NO;
}

   上面這段代碼是判斷手機號碼是否正確。創建一個phoneNumberRegEx的字符串,根據predicateWithFormat:創建一個NSPredicate對象表示一個條件,再用valuateWithObject判斷是否匹配.其中的lowercaseString是返回一個小寫的字符串(具體見我字符串經常使用用法的博客)。spa

  字符串中使用了不少iOS中的正則表達式(見我博客iOS經常使用正則表達式)。code

  iOS經常使用判斷代碼示例:orm

- (BOOL)validateUserName
{
    NSString *RegEx = @"^[\\d\\w_]{5,20}$";
    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", RegEx];
    BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]];
    return isCorrect ? YES : NO;
}

- (BOOL)validateUserNameNoChar
{
    NSString *phoneNumberRegEx = @"^[\\d_]{5,20}$";
    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumberRegEx];
    BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]];
    return isCorrect ? YES : NO;
}

- (BOOL)validatePhoneNumber
{
    // 手機號以13, 15,18開頭,八個 \d 數字字符
    NSString *phoneNumberRegEx = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$"; 
    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumberRegEx];
    BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]];
    return isCorrect ? YES : NO;
}

- (BOOL)validateEmail
{
    NSString *mailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mailRegEx];
    BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]];
    return isCorrect ? YES : NO;
}

- (BOOL)validateBlank
{
    NSString *priceRegEx =@"\\s*";
    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", priceRegEx];
    BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]];
    return isCorrect ? YES : NO;
}

- (BOOL)validatePrice
{
    NSString *priceRegEx =@"\\d*|\\d*\\.|\\d*\\.\\d{1,2}";
    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", priceRegEx];
    BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]];
    return isCorrect ? YES : NO;
}
相關文章
相關標籤/搜索