[iOS]正则匹配捕获组


   
    NSString *searchText = @" @+861345678888-昵称 大富翁收到";
    NSString *regexStr = @" @(\\+\\d+)-(.*) ";
    
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    
    NSArray *matches = [regex matchesInString:searchText
                                      options:0
                                        range:NSMakeRange(0, [searchText length])];
    
    if (matches.count>0) {
        
        //此方法只能获取一个整体的正则匹配
        for (NSTextCheckingResult *match in matches) {
            NSRange matchRange = [match range];
            NSString *matchString = [searchText substringWithRange:matchRange];
            NSLog(@"%@", matchString);
        }
        
        //捕获组用以下方法
        NSRange matchRange = [[matches firstObject] rangeAtIndex:1];
        NSString *matchString = [searchText substringWithRange:matchRange];
        NSLog(@"%@", matchString);
        
        NSRange matchRange2 = [[matches firstObject] rangeAtIndex:2];
        NSString *matchString2 = [searchText substringWithRange:matchRange2];
        NSLog(@"%@", matchString2);
    }
   
    
    
    /*
     
     2019-03-07 15:49:59.505905+0800 Demo[27094:6786924]  @+861345678888-昵称
     2019-03-07 15:49:59.506050+0800 Demo[27094:6786924] +861345678888
     2019-03-07 15:49:59.506173+0800 Demo[27094:6786924] 昵称
     
     */

你可能感兴趣的:([iOS]正则匹配捕获组)