ios拓展17-ios正则表达式

作者: Abler | 来源:发表于2016-08-08 10:31 被阅读156次

给大家来个简单的正则表达式操作

正则表达式匹配规则:http://www.runoob.com/regexp/regexp-syntax.html
正则表达式文章(如果想深究):http://deerchao.net/tutorials/regex/regex.htm

ps:正则表达式记不住也没关系,百度一下常用的正则表达式,一般都有 **如果经常用还是记住的好**.
+++***+++一般代码都一样,需要修改的也就是  匹配规则  和 需要匹配的字符串+++***+++

具体语法:

1. 创建正则表达式对象
    // 1.1 设置匹配规则++++++++++不懂规则语法点击上面链接+++++++++++
    NSString *pattern = @"a.*?c";// 匹配方案 @"a(.*?)c"

    // 1.2 设置匹配字符串的处理模式  ===>下面的options
    /*
    NSRegularExpressionCaseInsensitive             = 1 << 0,     // 不区分大小写字母模式
    NSRegularExpressionAllowCommentsAndWhitespace  = 1 << 1,     // 忽略掉正则表达式中的空格和#号之后的字符
    NSRegularExpressionIgnoreMetacharacters        = 1 << 2,     // 将正则表达式整体作为字符串处理
    NSRegularExpressionDotMatchesLineSeparators    = 1 << 3,     // 允许.匹配任何字符,包括换行符
    NSRegularExpressionAnchorsMatchLines           = 1 << 4,     // 允许^和$符号匹配行的开头和结尾
    NSRegularExpressionUseUnixLineSeparators       = 1 << 5,     // 设置\n为唯一的行分隔符,否则所有的都有效。
    NSRegularExpressionUseUnicodeWordBoundaries    = 1 << 6      // /使用Unicode TR#29标准作为词的边界,否则所有传统正则表达式的词边界都有效
    */

    // 1.3 创建正则表达式对象
    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:pattern
                                  options:NSRegularExpressionCaseInsensitive
                                  error:nil];
2. 开始匹配字符串
    // 2.1 设置需要匹配字符串
    NSString *matchString = @"dsampoewaf";

    // 2.2 设置进行匹配时的参数===>下面的options
    /*
    NSMatchingReportProgress         = 1 << 0,       // 找到最长的匹配字符串后调用block回调
    NSMatchingReportCompletion       = 1 << 1,       // 找到任何一个匹配串后都回调一次block
    NSMatchingAnchored               = 1 << 2,       // 从匹配范围的开始进行极限匹配
    NSMatchingWithTransparentBounds  = 1 << 3,       // 允许匹配的范围超出设置的范围
    NSMatchingWithoutAnchoringBounds = 1 << 4        // 禁止^和$自动匹配行开始和结束
    */

    // 2.3 设置匹配字符串的范围
    NSRange range = NSMakeRange(0, matchString.length);

    // 2.4 开始匹配
    NSArray<NSTextCheckingResult *> *textCheckingResults = [regex matchesInString:matchString
                                                                          options:NSMatchingReportProgress
                                                                            range:range];
3. 处理匹配的结果(根据正则表达式,获取到的结果)
    for (NSTextCheckingResult *result in textCheckingResults) {
        NSLog(@"textCheckingResults:%@",[matchString substringWithRange:result.range]);
    }
4.匹配时,有哪些字符串
NSTextCheckingResult *matchResult = [regex firstMatchInString:matchString options:NSMatchingReportProgress range:range];
    for (int i=0; i<matchResult.numberOfRanges; i++) {
        NSLog(@"匹配到的字符串:%@",[matchString substringWithRange:[matchResult rangeAtIndex:i]]);
    }

如字符串:@"http://www.jianshu.com/p/924a4a632bb9000"
匹配规则:@"http://w(.?)w.jianshu.com/p/924a(.?)32bb9"

打印结果

相关文章

网友评论

    本文标题:ios拓展17-ios正则表达式

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