正则表达式是正则表达式、正则表达式(Regular ExpREssion,在代码中经常简称为regex、regexp或re )、计算机科学的概念。 正则表达式使用单个字符串来描述和匹配一组符合语法规则的字符串。
从事iOS开发的童鞋,应该使用过正则表达式吧。 正则表达式有助于确定字符串是否合法。 例如:
制作APP注册页面时,需要判断手机号码是否采用正确的格式,是否足够11位数。
在反馈意见时,需要判断邮箱的格式是否正确。
手机号码的判断和邮件地址的判断应该是iOS开发者们最常用的。 具体如何判断,简单整理如下。
邮箱验证
(BOOL ) validate电子邮件: (ns string * )电子邮件
{
ns string * email regex=@ ' [ a-z0-9a-z._ %-] @ [ a-za-z0-9.- ]".[ a-za-z ] { 2,4 } ';
ns predicate * email test=[ nspredicatepredicatewithformat : @ ' self matches % @ ',emailRegex]
return [ emailtestevaluatewithobject :电子邮件];
}
NSPredicate是Foundation类,用于查询。 原理和用法类似于SQL的where。
确认手机号码
简单的判断方法
(BOOL ) validatephone:(nsstring* ) phone
{
ns string * phone regex=@ '1[3|5|7|8| ] [0-9] {9};
ns predicate * phone test=[ nspredicatepredicatewithformat : @ ' self matches % @ ',phoneRegex]
return [ phonetestevaluatewithobject : phone ];
}
这只是简单地判断手机号码的格式。 其实手机的格式有一点复杂。
详细的判断方法
//正规判断手机号码的格式
(BOOL ) validatephone:(nsstring* ) phone
{
//*
*手机号码
*移动: 134[0-8]、135、136、137、138、139、150、151、157、158、159、182、187和188
连通: 130、131、132、152、155、156、185、186
*电信: 133、1349、153、180、189
*/
ns string * mobile=@ ' ^1(3[0-9]|5 [0- 35-9 ]|8 [ 025-9 ] )\d{8}$ ';
//*
10 *中国移动: China移动
11 * 134[0-8],188
12 */
ns string * cm=@ ' ^1(34 [0-8]|(3[5-9]|5 [ 017-9 ]|8 [ 278 ] (d )\d{7}$ )d;
//*
15 *中国联通: China Unicom
16 * 130,186
17 */
ns string * Cu=@ ' ^1(3[0-2]|5 [ 256 ]|8 [ 56 ] (d {8} $ ' );
//*
20 *中国电信: China Telecom
21 * 133,189
2*/
nsstring*CT=@'^1((33|53|8[09] )0-9)|349 )\d{7}$ ';
//*
25 *大陆地区固话和小灵通
26 *区号: 010、020、021、022、023、024、025、027、028、029
27 *编号: 7位或8位
28 */
//ns string * PHS=@ ' ^0(10|2 [0- 5789 ]| d {3} (d { 7,8 } $ ' );
ns predicate * regextestmobile=[ nspredicatepredicatewithformat : @ ' self matches % @ ',MOBILE]
ns predicate * regextestcm=[ nspredicatepredicatewithformat : @ ' self matches % @ ',CM]
ns predicate * regextestcu=[ nspredicatepredicatewithformat : @ ' self matches % @ ',CU]
ns predicate * regextestct=[ nspredicatepredicatewithformat : @ ' self matches % @ ',CT]
((regextestmobileevaluatewithobject 3360 phone )==yes ) ) () ) ) ) )。
||(regextestcmevaluatewithobject : phone (==yes ) ) ) () () ) ) ) )。
||(regextestctevaluatewithobject : phone (==yes ) ) ) ) ) )。
||([ regextestcuevaluatewithobject : phone ]==yes ) )
{
注册文本虚拟对象:电话(==是) ) 0
nslog(@'Chinamobile );
} else if ([ regextestctevaluatewithobject 3360 phone ]==yes () ) ) )0)。
nslog(@'ChinaTelecom );
} else if (regextestcuevaluatewithobject 3360 phone (==yes ) ) ) )0)。
nslog(@'Chinaunicom );
} else {
nslog(@'unknow );
}
返回是;
}
else
{
返回否;
}
}
以上段落是判断手机号码的详细方法。 基本上这个判断就足够了。 如果有三大运营商,就会给出其他段的手机号码。 直接子啊,在上面做简单的修改就可以了。
作者热情的夏天正好是在线(www.superqq.com)站长,百度百家专栏作者
iOS工程师非知名媒体微信公众号iOS开发: iOSDevTip运营者