美文网首页
url正则匹配键值对

url正则匹配键值对

作者: 时光浅影 | 来源:发表于2019-03-13 16:59 被阅读0次
    NSString *urlStr = [NSString stringWithFormat:@"%@://para1=value1&para2=value2", @"thirdParty"];
        NSString *hString = [self paramValueOfUrl:urlStr withParam:@"para2"];
    
    //以url形式的字符串中获取某一个值
    - (NSString *)paramValueOfUrl:(NSString *)url withParam:(NSString *)param
    {
        
        NSError *error;
        NSString *regTags=[[NSString alloc] initWithFormat:@"(^||\\?)+%@=+([^&]*)(&|$)",param];
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&error];
        
        // 执行匹配的过程
        NSArray *matches = [regex matchesInString:url
                                          options:0
                                            range:NSMakeRange(0, [url length])];
        for (NSTextCheckingResult *match in matches) {
            NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
            return tagValue;
        }
        return nil;
    }
    

    相关文章

      网友评论

          本文标题:url正则匹配键值对

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