1. 程式人生 > >iOS 正則表示式判斷純數字以及匹配11位手機號碼

iOS 正則表示式判斷純數字以及匹配11位手機號碼

1用正則表示式 
//是否是純數字
+ (BOOL)isNumText:(NSString *)str{
    NSString * regex        = @"(/^[0-9]*$/)";
    NSPredicate * pred      = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch            = [pred evaluateWithObject:str];
    if (isMatch) {
        return YES;
    }else{
        return NO;
    }
}
具體正則對不對  還需要大家來看以下 
第二種 系統源生的 
我推薦第二種 
- (NSString *) trimming {
    
    return [self stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
}
//判斷是不是純數字
    [NSCharacterSet decimalDigitCharacterSet];
    if ([[textField.text stringByTrimmingCharactersInSet: [NSCharacterSet decimalDigitCharacterSet]]trimming].length >0) {
        DLog(@"不是純數字");
    }else{
        DLog(@"純數字!");
    }

最近在做一個即時通訊的專案, 首先是註冊登入介面, 專案需求是通過使用者輸入的手機號碼獲取一個4位數的驗證碼來完成註冊,那麼, 問題來了?

如何判斷使用者輸入的手機號碼是合法的正確的11位手機號碼呢?(這些簡單的問題就在前端判斷好了再post給後臺 ,沒必要把各種沒用的資料都post給後臺)

判斷手機號碼是否正確的方法很多,我是用正則表示式來完成匹配的,廢話不多說,直接上程式碼:

  1. //正則表示式匹配11位手機號碼
  2.     NSString *regex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";  
  3.     NSPredicate *pred = [NSPredicate
     predicateWithFormat:@"SELF MATCHES %@", regex];  
  4.     BOOL isMatch = [pred evaluateWithObject:_telField.text];  
  5. if(isMatch) {  //有效手機號
  6. }else//無效手機號
  7.     {  
  8.             if (ios7) {  
  9.                 UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"無效的手機號碼,請重新輸入..." delegate:self
     cancelButtonTitle:nil otherButtonTitles:@"確定", nil nil];  
  10.                 alertView.tag = 104;  
  11.                 [alertView show];  
  12.             }else
  13.             {  
  14.                 UIAlertController*alertController = [UIAlertController alertControllerWithTitle:nil message:@"無效的手機號碼,請重新輸入..." preferredStyle:UIAlertControllerStyleAlert];  
  15.                 UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction*action) {  
  16.                     [_telField selectAll:self];  
  17.                 }];  
  18.                 [alertController addAction:otherAction];  
  19.                 [self presentViewController:alertController animated:YES completion:nil];  
  20.             }  
  21.         }  
  22.     }  

聯通,移動和電信每年都會新增新的號碼,所以匹配電話號碼的正則表示式也要年年更新.

^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$這個正則表示式我測試過了還沒發現有匹配不了的號碼,在這裡分享給大家用!