2011-03-09 49 views
1

我正在尋找一種有效的方式來取代一個NSString(或的NSMutableString)與替換單詞「鏈接」網址中的網址,例如...iPhone目標C - 如何從一個NSString

@"This is a sample with **http://bitbanter.com** within the string and heres another **http://spikyorange.co.uk** for luck" 

謹以此成爲...

@"This is a sample with **'link'** within the string and heres another **'link'** for luck" 

理想情況下,我想這是某種方法接受正則表達式,但是,這需要在iPhone上工作,最好是沒有任何庫,或,如果圖書館很小,我可以被說服。

其他便於使用的功能,請將@"OMG"替換爲@"Oh my God",但不能當它是單詞的一部分,即不應觸及@"DOOMGAME"

任何建議表示讚賞。

Regards, Rob。

+0

這不應該太難找出 - 只需搜索以「http://」開頭的模式(注意http之前的空格),一旦找到,遍歷字符,直到找到另一個空間,因爲這將表明URL的結束。 – Rog 2011-03-09 21:17:17

回答

3

這實際上是一個有趣的玩,並希望解決方案以某種方式,你在找什麼。這足夠靈活,不僅適用於鏈接,還適用於其他模式,您可能希望使用某些條件替換另一個詞:

我已經評論了大部分代碼,因此它應該是非常明顯的。如果沒有,隨時發表評論,我會盡我所能的幫助:

- (NSString*)replacePattern:(NSString*)pattern withReplacement:(NSString*)replacement forString:(NSString*)string usingCharacterSet:(NSCharacterSet*)characterSetOrNil 
{ 
    // Check if a NSCharacterSet has been provided, otherwise use our "default" one 
    if (!characterSetOrNil) 
    characterSetOrNil = [NSCharacterSet characterSetWithCharactersInString:@" !?,()]"]; 

    // Create a mutable copy of the string supplied, setup all the default variables we'll need to use 
    NSMutableString *mutableString = [[[NSMutableString alloc] initWithString:string] autorelease]; 
    NSString *beforePatternString = nil; 
    NSRange outputrange = NSMakeRange(0, 0); 

    // Check if the string contains the "pattern" you're looking for, otherwise simply return it. 
    NSRange containsPattern = [mutableString rangeOfString:pattern]; 
    while (containsPattern.location != NSNotFound) 
    // Found the pattern, let's run with the changes 
    { 
     // Firstly, we grab the full string range 
     NSRange stringrange = NSMakeRange(0, [mutableString length]); 
     NSScanner *scanner = [[NSScanner alloc] initWithString:mutableString]; 

     // Now we use NSScanner to scan UP TO the pattern provided 
     [scanner scanUpToString:pattern intoString:&beforePatternString]; 

     // Check for nil here otherwise you will crash - you will get nil if the pattern is at the very beginning of the string 
     // outputrange represents the range of the string right BEFORE your pattern 
     // We need this to know where to start searching for our characterset (i.e. end of output range = beginning of our pattern) 
     if (beforePatternString != nil) 
      outputrange = [mutableString rangeOfString:beforePatternString]; 

     // Search for any of the character sets supplied to know where to stop. 
     // i.e. for a URL you'd be looking at non-URL friendly characters, including spaces (this may need a bit more research for an exhaustive list) 
     NSRange characterAfterPatternRange = [mutableString rangeOfCharacterFromSet:characterSetOrNil options:NSLiteralSearch range:NSMakeRange(outputrange.length, stringrange.length-outputrange.length)]; 

     // Check if the link is not at the very end of the string, in which case there will be no characters AFTER it so set the NSRage location to the end of the string (== it's length) 
     if (characterAfterPatternRange.location == NSNotFound) 
      characterAfterPatternRange.location = [mutableString length]; 

     // Assign the pattern's start position and length, and then replace it with the pattern 
     NSInteger patternStartPosition = outputrange.length; 
     NSInteger patternLength = characterAfterPatternRange.location - outputrange.length; 
     [mutableString replaceCharactersInRange:NSMakeRange(patternStartPosition, patternLength) withString:replacement]; 
     [scanner release]; 

     // Reset containsPattern for new mutablestring and let the loop continue 
     containsPattern = [mutableString rangeOfString:pattern]; 
    } 
    return [[mutableString copy] autorelease]; 
} 

,並使用你的問題作爲一個例子,這裏是你如何可以把它稱爲:

NSString *firstString = @"OMG!!!! this is the best convenience method ever, seriously! It even works with URLs like http://www.stackoverflow.com"; 
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@" !?,()]"]; 
NSString *returnedFirstString = [self replacePattern:@"OMG" withReplacement:@"Oh my God" forString:firstString usingCharacterSet:characterSet]; 
NSString *returnedSecondString = [self replacePattern:@"http://" withReplacement:@"LINK" forString:returnedFirstString usingCharacterSet:characterSet]; 
NSLog (@"Original string = %@\nFirst returned string = %@\nSecond returned string = %@", firstString, returnedFirstString, returnedSecondString); 

希望它有助於! 歡呼聲, Rog

+0

Rog,感謝您花時間編寫解決方案,我應該可以直接插入,我真的很感激!調用它的示例代碼看起來像我希望的那樣簡單。 – 2011-03-10 07:19:28

+0

characterSetWithCharactersInString用於確定單詞中的中斷嗎?它看起來像是用來確保OMG是開始行還是周圍的其中一個分隔符? – 2011-03-10 07:20:32

+0

是的,這是正確的,所以該方法首先查找pattern =「OMG」,然後查找字符集中的任何字符(包括空格)。一旦找到,它將使用替換字符串代替「OMG」。 – Rog 2011-03-10 09:42:28

0

從iOS 4開始,可以使用NSRegularExpression。除此之外,您可以通過塊枚舉字符串中的所有匹配項,從而可以根據自己的需要執行任何操作,或者讓正則表達式直接爲您執行某些替換。

直接字符串替換(如「OMG」 - >「噢,我的上帝」)可以直接通過一個NSString使用-stringByReplacingOccurencesOfString:withString:,或replaceOccurrencesOfString:withString:options:range:如果你的字符串是可變的執行。