0

尝试从文本中删除所有网址:

- (NSString *)cleanText:(NSString *)text{
    NSString *string = @"This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it.";
    NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
    NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];

    for (NSTextCheckingResult *match in matches) {
        if ([match resultType] == NSTextCheckingTypeLink) {
            NSString *matchingString = [match description];
            NSLog(@"found URL: %@", matchingString);
            string = [string stringByReplacingOccurrencesOfString:matchingString withString:@""];
        }
    }
    NSLog(string);
    return string;
}

但是string返回不变(有匹配)。

更新:控制台输出:

found URL: <NSLinkCheckingResult: 0xb2b03f0>{22, 36}{http://abc.com/efg.php?EFAei687e3EsA}
2013-10-02 20:19:52.772 
This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it and a number 097843.

@Raphael Schweikert 完成的现成工作配方。

4

2 回答 2

2

问题是[match description]不返回匹配的字符串;它返回一个如下所示的字符串:

"<NSLinkCheckingResult: 0x8cd5150>{22,36}{http://abc.com/efg.php?EFAei687e3EsA}"

要替换字符串中匹配的 URL,您应该执行以下操作:

string = [string stringByReplacingCharactersInRange:match.range withString:@""];
于 2013-10-02T16:20:38.777 回答
1

根据Apple 自己的 Douglas Davidson 的说法,匹配项保证按照它们在字符串中出现的顺序排列。matches因此,与其对数组进行排序(如我所建议的那样),不如对其进行反向迭代。

整个代码示例将如下所示:

NSString *string = @"This is a sample of a http://abc.com/efg.php sentence (http://abc.com/efg.php) with a URL within it and some more text afterwards so there is no index error.";
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:0|NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in [matches reverseObjectEnumerator]) {
    string = [string stringByReplacingCharactersInRange:match.range withString:@""];
}

可以省略检查,match.resultType == NSTextCheckingTypeLink因为您已经在选项中指定了您只对链接感兴趣。

于 2013-10-02T16:57:37.357 回答