Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 239
Bryan Vorel Avatar asked May 05 '11 20:05

Bryan Vorel


1 Answers

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.

like image 73
Nick Weaver Avatar answered Oct 22 '22 02:10

Nick Weaver