当前位置: 移动技术网 > IT编程>开发语言>正则 > iOS 正则表达式判断纯数字及匹配11位手机号码的方法

iOS 正则表达式判断纯数字及匹配11位手机号码的方法

2017年12月08日  | 移动技术网IT编程  | 我要评论
第一种使用正则表达式 判断 //是否是纯数字 + (bool)isnumtext:(nsstring *)str{ nsstring *

第一种使用正则表达式 判断

//是否是纯数字 
+ (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给后台)

判断手机号码是否正确的方法很多,我是用正则表达式来完成匹配的,废话不多说,直接上代码:

//正则表达式匹配11位手机号码 
 nsstring *regex = @"^((13[0-9])|(15[^4,\\d])|(18[0,0-9]))\\d{8}$"; 
 nspredicate *pred = [nspredicate predicatewithformat:@"self matches %@", regex]; 
 bool ismatch = [pred evaluatewithobject:_telfield.text]; 
if(ismatch) { //有效手机号 
}else//无效手机号 
 { 
   if (ios7) { 
    uialertview *alertview = [[uialertview alloc]initwithtitle:nil message:@"无效的手机号码,请重新输入..." delegate:self cancelbuttontitle:nil otherbuttontitles:@"确定", nil nil]; 
    alertview.tag = 104; 
    [alertview show]; 
   }else 
   { 
    uialertcontroller*alertcontroller = [uialertcontroller alertcontrollerwithtitle:nil message:@"无效的手机号码,请重新输入..." preferredstyle:uialertcontrollerstylealert]; 
    uialertaction *otheraction = [uialertaction actionwithtitle:@"确定" style:uialertactionstyledefault handler:^(uialertaction*action) { 
     [_telfield selectall:self]; 
    }]; 
    [alertcontroller addaction:otheraction]; 
    [self presentviewcontroller:alertcontroller animated:yes completion:nil]; 
   } 
  } 
 } 

联通,移动和电信每年都会添加新的号码,所以匹配电话号码的正则表达式也要年年更新.

^((13[0-9])|(15[^4,\\d])|(18[0,0-9]))\\d{8}$这个正则表达式我测试过了还没发现有匹配不了的号码,在这里分享给大家用!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网