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、方法二: 值替换
/// 方法二:
- (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;
}