替换主字符串中的多个不同子字符串

时间:2017-02-15 15:32:08

标签: ios objective-c string

我有一个URL字符串,我需要用。替换值。

例如:

HTTP:\\ www.domain.com \ ID = [USER_ID] &安培;记录= [CALL_KEY] &安培;一些其它= [ OTHER_STUFF]

我需要遍历字符串,寻找 [] ,然后将其替换为内部的任何内容。

现在,我必须对每个单独的密钥进行硬编码并将其替换为值。

- (NSString*) injectValuesIntoURL:(NSString*) url{


    NSString * injected = @"";

    //[CALL KEY]
    injected = [url stringByReplacingOccurrencesOfString:@"[CALL_KEY]" withString:[[NSUserDefaults standardUserDefaults] objectForKey:@"kCallKey"]];

    //[USER_ID]
    injected = [injected stringByReplacingOccurrencesOfString:@"[USER_ID]" withString:[[NSUserDefaults standardUserDefaults] objectForKey:@"kUsername"]];

        //[OTHER_STUFF]
        injected = [injected stringByReplacingOccurrencesOfString:@"[OTHER_STUFF]" withString:[[NSUserDefaults standardUserDefaults] objectForKey:@"kOtherStuff"]];


    return injected;

}

我有一堆可以插入的不同值,而不是硬编码[CALL KEY],我想动态读取其中的内容并注入值。所以初始URL可能是

HTTP:\\ www.domain.com \ ID = [kUsername] &安培;记录= [kCallKey] &安培;一些其它= [ kOtherStuff]

所以我可以循环查找[]的字符串并将其替换为内部的任何内容。

如何搜索字符串并找到 [ 字符,然后将该字符串复制到 ] ,然后继续下一个[等等?

2 个答案:

答案 0 :(得分:0)

我通过这种方式解决了类似的问题,我使用了一个字典,其中存储了关键字以便替换关键字,并将值替换为字符串。

NSDictionary * stringsReplacedByDictionary = NSDictionary *dictionary = @{
@"kUserName" : Username,
@"kCallKey" : CallKey,
@"kOtherStuff" : otherStuff 
};

// Enumerate the Dictionary containg all Strings to be replaced.
for (NSString *keys in stringsReplacedByDictionary) {

// Here I builded the search string in your case would be [kUsername]
NSString *keysWithParenthesis = [NSString stringWithFormat:@"[$%@]", keys];
NSString *value = [stringsReplacedByDictionary objectForKey:keys];


 //Check if there is a string to replace!
 if ([stringToScan containsString:keysWithParenthesis]) {
 NSRange replacingStringRange = [[textStorage string] rangeOfString:keysWithParenthesis];
 [textStorage replaceCharactersInRange:replacingStringRange withString:value];
        }

答案 1 :(得分:0)

试试这个

    NSString *url = @"http:\\www.domain.com\\id=[USER_ID]&record=[CALL_KEY]&someother=[OTHER_STUFF]";
    NSArray *values = @[@"one", @"two", @"three"];
    NSString *pattern = @"\\[([^\\]\\[]+)]";

    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
    NSInteger count = [regex matchesInString:url options:0 range:NSMakeRange(0, url.length)].count;

    if (count == 0 || count != values.count) {
        // handle error ..
    }

    NSTextCheckingResult *result = [regex firstMatchInString:url options:0 range:NSMakeRange(0, url.length)];

    for (int i = 0; i < values.count; i++) {
        url = [url stringByReplacingCharactersInRange:result.range withString:values[i]];
        result = [regex firstMatchInString:url options:0 range:NSMakeRange(0, url.length)];

        if (result.range.location == NSNotFound) { // optional
            break;
        }
    }

    NSLog(@"%@", url);