开发者

NSRegularExpression: Replace url text with <a> tags

I am currently using a UIWebView to stylize posts from twitter. Some tweets of course contain URL's, but do not contain the <a> tags. I am able to pull out the URL, however I am not sure how to add the <a> tags and place back into the tweet. I will then use the same approach here to add links to the @usernames and #hashtags. Here is an example of my current code:

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

Ultimately, I would like the final string to look like this:

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>

Any help would be much appreciated.


And here is an objective-c version:

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

I did something like this before, but I used javascript to do it. When the view has loaded, use the delegate method webViewDidFinishLoad, and inject 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];
} 

Here's the javascript call in a non objective-c nsstring quotes version:

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

The regex is not perfect but will catch most of the links.


You could use stringByReplacingOccurrencesOfString:withString: to search for your match and replace it with the HTML link.

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

(You might also use the range that you get from rangeOfFirstMatchInString:options:range in stringByReplacingCharactersInRange:withString: but I'm not sure what happens you pass a string thats longer than the ranges length in this case).

Note that your search will only find the first link in a tweet, and if there are several matches you'll miss those.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜