iOS之正则

作者: 平安喜乐698 | 来源:发表于2019-08-19 11:15 被阅读0次
 目录

什么是正则

用字符串来描述一种规则特征,去验证另一个字符串是否符合该特征。

由普通字符和特殊字符组成。

正则可以用来

1、用来验证字符串是否符合指定特征(例:是否合法邮箱地址、手机号、身份证号)。
2、用来查找字符串,从一个长的文本中查找符合指定特征的字符串,比如查找固定字符串更加灵活便捷。
3、用来替换字符串(查找到之后替换)。

规则如下

特殊字符 含义
. 任意一个字符(除换行符)
[^x] 任意非x的字符
\d 任意单个数字(\d匹配的是Unicode,会进行各种语言筛选。没有[0-9]效率高,仅是阿拉伯数字)
\D 任意非数字
\s 任意空白符
\S 任意非空白符
\w 任意一个字符或数字
\W 任意一个非字符或非数字
0-9 具体的数字
[A-Z]、[0-9]、[a-z]、[A-Za-z]、[A-Za-z0-9]、[013]、[abc]、[013-5] 闭集合元素之一
^ 字符串开头
$ 字符串结尾
|
\ 转义字符前要加(如\d,\.)(对于无效转义字符则忽略\)(对于特殊字符则需要前加\,例如\. \?)
( ) 控制范围
特殊字符(修饰作用:修饰前面那个字符) 含义
为0个或1个
* 重复0次或多次
+ 重复1次或多次
{n} 长度为n(前面的字符)
{n,} 长度为n或n+
{n,m} 长度为n到m
特殊字符(修饰作用:修饰后面字符串) 含义
?: 非获取匹配 (例:hello (?:sx) ,@"hello sx hello" 匹配到的字符串为hello sx)
?= 非获取匹配 (例:hello (?=sx) ,@"hello sx hello" 匹配到的字符串为hello)

用例1:验证字符串(验证手机号,仅作为示例使用)

    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0-9])|(14[57])|(17[013678]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    if( [phoneTest evaluateWithObject:@"18888888888"]){         
    }else{
    }

用例2:查找字符串

    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0-9])|(14[57])|(17[013678]))\\d{8}$";
NSRange range = [@"zzz18888888888" rangeOfString:phoneRegex options:NSRegularExpressionSearch];
    if (range.location != NSNotFound) {
        // 找到
        NSLog(@"%@",NSStringFromRange(range));
    }else{
        //未找到
    }
    NSError *error;
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0-9])|(14[57])|(17[013678]))\\d{8}$";
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:phoneRegex options:0 error:&error];
    if (!error) {
        NSTextCheckingResult *match = [regular firstMatchInString:@"zzz18888888888" options:0 range:NSMakeRange(0, [mobilePhone length])];
        if (match) {
            NSString *result = [mobilePhone substringWithRange:match.range];
            NSLog(@"%@",result);
        }
    }else{
        NSLog(@"error -- %@",error);
    }

相关文章

网友评论

    本文标题:iOS之正则

    本文链接:https://www.haomeiwen.com/subject/xrzjsctx.html