정규 URL 문자열의 값 바꾸기

2240 단어
1. 방법 1: 키와 값을 함께 바꾸기
- (NSString *) paramValueOfUrl:(NSString *) url withParam:(NSString *) param value:(NSString *)value{
    
    NSError *error;

    NSString *targetString = [NSString stringWithFormat:@"%@=%@",param,value];

    NSString *regTags = [[NSString alloc] initWithFormat:@"%@=+([\\w]*)",param];

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags options:0 error:&error];

    NSString *string = [regex stringByReplacingMatchesInString:url
                                                       options:0
                                                         range:NSMakeRange(0, [url length])
                                                  withTemplate:targetString];

    return string;
}


2. 방법 2: 값 바꾸기
///  :
- (NSString *) paramValueOfUrl2:(NSString *) url withParam:(NSString *) param value:(NSString *)value{

        NSError *error;
    
        //  (^|&|\\?|#)+%@=+([^&|#]*)(#|&|$) : range   [match rangeAtIndex:2]
        //  %@=+([^&|#]*)(#|&|$)   : range   [match rangeAtIndex:1]
        //   numberOfRanges ,  [url substringWithRange:[match rangeAtIndex:i]]
        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) {
            NSRange range = [match rangeAtIndex:2];
            NSString *tagValue = [url substringWithRange:range];  //  2 
            if (![value isEqualToString:tagValue]) {
                url = [url stringByReplacingCharactersInRange:range withString:value];
            }
        }
        return url;
}

좋은 웹페이지 즐겨찾기