1

NSString(またはNSMutableString)のURLを置換単語「link」に置き換える効率的な方法を探しています。たとえば...

@"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"触れてはいけない場合は置き換えません。

任意の提案をいただければ幸いです。

よろしく、ロブ。

4

2 に答える 2

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);

お役に立てば幸いです。乾杯、ログ

于 2011-03-10T02:05:24.073 に答える
0

iOS 4以降、NSRegularExpressionが利用可能になりました。特に、ブロックを介して文字列内のすべての一致を列挙して、それぞれがやりたいことを実行したり、正規表現にある種の置換を直接実行させたりすることができます。

文字列の直接置換('OMG'->'Oh my God'など)は、 -stringByReplacingOccurencesOfString:withString:、または文字列が可変の場合はreplaceOccurrencesOfString:withString:options:range:を使用して、NSStringによって直接実行できます。

于 2011-03-09T21:17:36.863 に答える