iPhone Objective C - 如何从 NSString 中删除 URL

发布于 2024-10-21 06:23:18 字数 584 浏览 2 评论 0 原文

我正在寻找一种有效的方法来用替换词“link”替换 NSString(或 NSMutableString)中的 URL,例如...

@"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 “ 不应该被触摸。

任何建议表示赞赏。

问候, 抢。

I am looking for an efficient way to replace URLs in an NSString (or NSMutableString) with the replacement word 'link', for example ...

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

I would like this to become...

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

Ideally, I would like this to be some sort of method that accepts regular expressions, but, this needs to work on the iPhone, preferably without any libraries, or, I could be persuaded if the library was tiny.

Other features that would be handy, replace @"OMG" with @"Oh my God", but not when it's part of a word, i.e. @"DOOMGAME" shouldn't be touched.

Any suggestions appreciated.

Regards,
Rob.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

狂之美人 2024-10-28 06:23:18

这实际上玩起来相当有趣,希望该解决方案在某种程度上正是您所寻找的。这足够灵活,不仅可以满足链接的需要,还可以满足您可能希望使用某些条件将一个单词替换为另一个单词的其他模式:

我已经注释了大部分代码,因此它应该是非常不言自明的。如果没有,请随时发表评论,我会尽力提供帮助:

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

我希望它有帮助!
干杯,
罗格

This was actually quite a bit of fun to play with and hopefully the solution is somehow what you were looking for. This is flexible enough to cater not only for links, but also other patterns where you may want to replace a word for another using certain conditions:

I have commented most of the code so it should be pretty self explanatory. If not, feel free to leave a comment and I will try my best to help:

- (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];
}

And to use your question as an example, here's how you could call it:

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

I hope it helps!
Cheers,
Rog

花开柳相依 2024-10-28 06:23:18

从 iOS 4 开始,NSRegularExpression可用。除此之外,您可以通过块枚举字符串中的所有匹配项,从而允许您对每个匹配项执行任何您想要的操作,或者让正则表达式直接为您执行某种替换。

直接字符串替换(如“OMG”->“Oh my God”)可以通过 NSString 直接执行,使用 -stringByReplacingOccurencesOfString:withString:replaceOccurrencesOfString:withString:options:range: 如果您的字符串是可变的。

As of iOS 4, NSRegularExpression is available. Amongst other things, you can enumerate all matches within a string via a block, allowing you to do whatever you want to each, or have the regular expression perform some kinds of substitution directly for you.

Direct string substitutions (like 'OMG' -> 'Oh my God') can be performed directly by an NSString, using -stringByReplacingOccurencesOfString:withString:, or replaceOccurrencesOfString:withString:options:range: if your string is mutable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文