NSRegularExpression:用<a> tags</a>替换网址文字

时间:2011-05-05 20:21:12

标签: iphone objective-c regex ios

我目前正在使用UIWebView来设计来自twitter的帖子。有些推文当然包含URL,但不包含<a>标签。我可以提取网址,但是我不知道如何添加<a>标记并将其放回到推文中。然后,我将使用相同的方法添加@usernames和#hashtags的链接。以下是我当前代码的示例:

NSString *tweet = @"Sync your files to your Google Docs with a folder on your desktop.  Like Dropbox.  Good choice, Google storage is cheap. http://ow.ly/4OaOo";

NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))" options:NSRegularExpressionCaseInsensitive error:NULL];

NSString *match = [tweet substringWithRange:[expression rangeOfFirstMatchInString:tweet options:NSMatchingCompleted range:NSMakeRange(0, [tweet length])]];
NSLog(@"%@", match);// == http://ow.ly/4OaOo

最终,我希望最终的字符串看起来像这样:

Sync your files to your Google Docs with a folder on your desktop. Like Dropbox. Good choice, Google storage is cheap. <a href="http://ow.ly/4OaOo>http://ow.ly/4OaOo</a>

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:15)

这是一个Objective-c版本:

NSString *regexToReplaceRawLinks = @"(\\b(https?):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])";   

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceRawLinks
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSString *string = @"Sync your files to your Google Docs with a folder on your desktop.  Like Dropbox.  Good choice, Google storage is cheap. http://ow.ly/4OaOo";

NSString *modifiedString = [regex stringByReplacingMatchesInString:string
                                                           options:0
                                                             range:NSMakeRange(0, [string length])
                                                      withTemplate:@"<a href=\"$1\">$1</a>"];

NSLog(@"%@", modifiedString);

之前我做过类似的事,但我用javascript做了。加载视图后,使用委托方法webViewDidFinishLoad,并注入javascript:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *jsReplaceLinkCode = 
        @"document.body.innerHTML = " 
        @"document.body.innerHTML.replace("
            @"/(\\b(https?):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/ig, "
            @"\"<a href='$1'>$1</a>\""
    @");";

    [webVew stringByEvaluatingJavaScriptFromString:jsReplaceLinkCode];
} 

这是非Objective-c nsstring引用版本中的javascript调用:

document.body.innerHTML = document.body.innerHTML.replace(
      /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, 
      "<a href='document.location=$1'>$1</a>"
);

正则表达式并不完美,但会抓住大部分链接。

答案 1 :(得分:0)

您可以使用stringByReplacingOccurrencesOfString:withString:搜索match并将其替换为HTML链接。

NSString *htmlTweet = [tweet stringByReplacingOccurrencesOfString:match withString:html];

(你可能也使用rangeOfFirstMatchInString:options:range stringByReplacingCharactersInRange:withString:中的{{1}}范围,但我不确定你传递的字符串长度超过范围长度会发生什么在这种情况下)。

请注意,您的搜索只会在推文中找到第一个链接,如果有多个匹配,您将会错过这些链接。