Iphone NSRegularExpression:将url文本替换为<;a>;标签
我目前正在使用UIWebView对来自twitter的帖子进行样式化。一些推文当然包含URL,但不包含Iphone NSRegularExpression:将url文本替换为<;a>;标签,iphone,objective-c,regex,ios,Iphone,Objective C,Regex,Ios,我目前正在使用UIWebView对来自twitter的帖子进行样式化。一些推文当然包含URL,但不包含 任何帮助都将不胜感激。您可以使用stringByReplacingOccurrencesOfString:withString:搜索您的匹配项,并将其替换为HTML链接 NSString *htmlTweet = [tweet stringByReplacingOccurrencesOfString:match withString:html]; (您也可以使用从rangeOfFirstMa
任何帮助都将不胜感激。您可以使用
stringByReplacingOccurrencesOfString:withString:
搜索您的匹配项
,并将其替换为HTML链接
NSString *htmlTweet = [tweet stringByReplacingOccurrencesOfString:match withString:html];
(您也可以使用从rangeOfFirstMatchInString:options:range
中的range
获取的范围,方法是通过replacingCharactersRange:withString:,但我不确定在这种情况下传递的字符串长度是否超过范围长度)
请注意,您的搜索只会找到tweet中的第一个链接,如果存在多个匹配项,您将错过这些链接。以下是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);
以下是非objective-c nsstring quotes版本中的javascript调用:
document.body.innerHTML = document.body.innerHTML.replace(
/(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
"<a href='document.location=$1'>$1</a>"
);
document.body.innerHTML=document.body.innerHTML.replace(
/(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~(u124;)!:,.;]*[-A-Z0-9+&/%=~(u124;])/ig,
""
);
正则表达式并不完美,但可以捕获大部分链接。这将非常完美。我从未想过使用Javascript。使用js可能会很慢,也请检查我的obj-c解决方案。在这种情况下,如果我们使用regex两次,可以添加相同的链接,再次感谢您的快速响应!关于只查找第一个链接,您确实有一个正确的观点,需要修改我的代码。
- (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];
}
document.body.innerHTML = document.body.innerHTML.replace(
/(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
"<a href='document.location=$1'>$1</a>"
);