Java:用可点击的 HTML 链接替换文本 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1909534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java : replacing text URL with clickable HTML link
提问by Dough
I am trying to do some stuff with replacing String containing some URL to a browser compatible linked URL.
我正在尝试做一些事情,将包含一些 URL 的字符串替换为浏览器兼容的链接 URL。
My initial String looks like this :
我的初始字符串如下所示:
"hello, i'm some text with an url like http://www.the-url.com/ and I need to have an hypertext link !"
What I want to get is a String looking like :
我想要的是一个看起来像的字符串:
"hello, i'm some text with an url like <a href="http://www.the-url.com/">http://www.the-url.com/</a> and I need to have an hypertext link !"
I can catch URL with this code line :
我可以使用以下代码行捕获 URL:
String withUrlString = myString.replaceAll(".*://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"null\">HereWasAnURL</a>");
Maybe the regexp expression needs some correction, but it's working fine, need to test in further time.
也许正则表达式需要一些更正,但它工作正常,需要进一步测试。
So the question is how to keep the expression catched by the regexp and just add a what's needed to create the link : catched string
所以问题是如何保持正则表达式捕获的表达式并添加创建链接所需的内容:捕获的字符串
Thanks in advance for your interest and responses !
预先感谢您的关注和回复!
采纳答案by Martijn Courteaux
Try to use:
尝试使用:
myString.replaceAll("(.*://[^<>[:space:]]+[[:alnum:]/])", "<a href=\"\">HereWasAnURL</a>");
I didn't check your regex.
我没有检查你的正则表达式。
By using ()you can create groups. The $1indicates the group index.
$1will replace the url.
通过使用 ()您可以创建组。该$1指示组索引。
$1将替换网址。
I asked a simalir question: my question
Some exemples: Capturing Text in a Group in a regular expression
我问了一个 simalir 问题:我的问题
一些例子:在正则表达式中捕获组中的文本
回答by Paul Croarkin
public static String textToHtmlConvertingURLsToLinks(String text) {
if (text == null) {
return text;
}
String escapedText = HtmlUtils.htmlEscape(text);
return escapedText.replaceAll("(\A|\s)((http|https|ftp|mailto):\S+)(\s|\z)",
"<a href=\"\"></a>");
}
There may be better REGEXs out there, but this does the trick as long as there is white space after the end of the URL or the URL is at the end of the text. This particular implementation also uses org.springframework.web.util.HtmlUtils to escape any other HTML that may have been entered.
那里可能有更好的 REGEX,但只要 URL 末尾有空格或 URL 位于文本末尾,这就可以解决问题。此特定实现还使用 org.springframework.web.util.HtmlUtils 来转义可能已输入的任何其他 HTML。
回答by Sonson123
For anybody who is searching a more robust solution I can suggest the Twitter Text Libraries.
对于任何正在寻找更强大解决方案的人,我可以推荐Twitter 文本库。
Replacing the URLs with this library works like this:
用这个库替换 URL 的工作方式如下:
new Autolink().autolink(plainText)
回答by walkeros
Belows code replaces links starting with "http" or "https", links starting just with "www." and finally replaces also email links.
下面的代码替换了以“http”或“https”开头的链接,只以“www”开头的链接。最后还替换了电子邮件链接。
Pattern httpLinkPattern = Pattern.compile("(http[s]?)://(www\.)?([\S&&[^.@]]+)(\.[\S&&[^@]]+)");
Pattern wwwLinkPattern = Pattern.compile("(?<!http[s]?://)(www\.+)([\S&&[^.@]]+)(\.[\S&&[^@]]+)");
Pattern mailAddressPattern = Pattern.compile("[\S&&[^@]]+@([\S&&[^.@]]+)(\.[\S&&[^@]]+)");
String textWithHttpLinksEnabled =
"ajdhkas www.dasda.pl/asdsad?asd=sd www.absda.pl [email protected] klajdld http://dsds.pl httpsda http://www.onet.pl https://www.onsdas.plad/dasda";
if (Objects.nonNull(textWithHttpLinksEnabled)) {
Matcher httpLinksMatcher = httpLinkPattern.matcher(textWithHttpLinksEnabled);
textWithHttpLinksEnabled = httpLinksMatcher.replaceAll("<a href=\"ajdhkas <a href="http://www.dasda.pl/asdsad?asd=sd" target="_blank">www.dasda.pl/asdsad?asd=sd</a> <a href="http://www.absda.pl" target="_blank">www.absda.pl</a> <a href="mailto:[email protected]">[email protected]</a> klajdld <a href="http://dsds.pl" target="_blank">http://dsds.pl</a> httpsda <a href="http://www.onet.pl" target="_blank">http://www.onet.pl</a> <a href="https://www.onsdas.plad/dasda" target="_blank">https://www.onsdas.plad/dasda</a>
\" target=\"_blank\">myString.replaceAll(....., "<a href=\"\"></a>")
</a>");
final Matcher wwwLinksMatcher = wwwLinkPattern.matcher(textWithHttpLinksEnabled);
textWithHttpLinksEnabled = wwwLinksMatcher.replaceAll("<a href=\"http://text.replaceAll("(\s|\^|\A)((http|https|ftp|mailto):\S+)(\s|\$|\z)",
"<a href=''></a>");
\" target=\"_blank\">private static final Pattern urlPattern = Pattern.compile(
"(\s|\^|\A)((http|https|ftp|mailto):\S+)(\s|\$|\z)");
String userText = ""; // user content from db
String replacedValue = HtmlUtils.htmlEscape(userText);
replacedValue = urlPattern.matcher(replacedValue).replaceAll("<a href=\"\"></a>");
replacedValue = StringUtils.replace(replacedValue, "\n", "<br>");
System.out.println(replacedValue);
</a>");
final Matcher mailLinksMatcher = mailAddressPattern.matcher(textWithHttpLinksEnabled);
textWithHttpLinksEnabled = mailLinksMatcher.replaceAll("<a href=\"mailto:##代码##\">##代码##</a>");
System.out.println(textWithHttpLinksEnabled);
}
Prints:
印刷:
##代码##回答by Matt
Assuming your regex works to capture the correct info, you can use backreferences in your substitution. See the Java regexp tutorial.
假设您的正则表达式可以捕获正确的信息,您可以在替换中使用反向引用。请参阅Java 正则表达式教程。
In that case, you'd do
在那种情况下,你会做
##代码##回答by alaster
In case of multiline text you can use this:
如果是多行文本,您可以使用:
##代码##And here is full example of my code where I need to show user's posts with urls in it:
这是我的代码的完整示例,我需要在其中显示包含 url 的用户帖子:
##代码##
