NSRegularExpression: Replace url text with tags

前端 未结 2 885
逝去的感伤
逝去的感伤 2021-01-12 02:43

I am currently using a UIWebView to stylize posts from twitter. Some tweets of course contain URL\'s, but do not contain the tags. I am able to pull o

相关标签:
2条回答
  • 2021-01-12 03:09

    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.

    0 讨论(0)
  • 2021-01-12 03:09

    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 讨论(0)
提交回复
热议问题