Bry*_*rel 9 regex iphone objective-c ios
我目前正在使用UIWebView来设计来自twitter的帖子.一些推文当然包含URL,但不包含<a>标签.我能够提取URL,但是我不知道如何添加<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
Run Code Online (Sandbox Code Playgroud)
最终,我希望最终的字符串看起来像这样:
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>
任何帮助将非常感激.
Nic*_*ver 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);
Run Code Online (Sandbox Code Playgroud)
之前我做过类似的事情,但我用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];
}
Run Code Online (Sandbox Code Playgroud)
这是非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>"
);
Run Code Online (Sandbox Code Playgroud)
正则表达式并不完美,但会捕获大部分链接.
| 归档时间: |
|
| 查看次数: |
6142 次 |
| 最近记录: |