2013-01-17 29 views
0

我有以下網址:發現在URL格式的字符的索引/位置

http://test.me/s/hq6aN 

我基本上是想替換S採用的d,什麼是很容易做到這一點使用NSRegularExpression的最佳方式?基本上我想要的是找出/ s /中字符串的索引有什麼想法?

這是我到目前爲止有:

NSString *regexStr = @"/s/"; 
    NSError *error = nil; 
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error]; 
    NSArray *matches = [regex matchesInString:shortLink options:0 range:NSMakeRange(0, [shortLink length])]; 
    if ([matches count] > 0){ 
     NSTextCheckingResult *matchesIndex = [matches objectAtIndex:0]; 
     NSRange range = matchesIndex.range; 
    } 

我敢肯定我做錯了什麼與regexStr

+1

[url stringByReplacingOccurrencesOfString:@「/ s /」withString:@「/ d /」];'?這裏有使用正則表達式的其他原因嗎? – iDev

+0

哈,現在你提到了,我的答案**看起來像是過度殺傷。 – warrenm

回答

0

你的模式看起來不錯,但有這樣做的一個便捷方法搜索 - 和 - 替換,使您可以更簡潔地寫:

NSError *error = nil; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"/s/" options:0 error:&error]; 
NSMutableString *haystack = [NSMutableString stringWithString:@"http://test.me/s/hq6aN"]; 
[regex replaceMatchesInString:haystack options:0 range:NSMakeRange(0, [haystack length]) withTemplate:@"/d/"]; 

沒有爲NSStrings等效-stringByReplacingMatchesInString:options:range:withTemplate:如果您希望保留包含原始URL的字符串不可變。

相關問題