我的正则表达式检测字符串中的URL的问题? [英] issues with my regex to detect urls in a string?
问题描述
致以问候。
我使用以下正则表达式来检测字符串
中的url并将它们包装在< a>标签
Greetings all. I am using the following regex to detect urls in a string and wrap them inside the < a > tag
public static String detectUrls(String text) {
String newText = text
.replaceAll("(?:https?|ftps?|http?)://[\\w/%.-?&=]+",
"<a href='$0'>$0</a>").replaceAll(
"(www\\.)[\\w/%.-?&=]+", "<a href='http://$0'>$0</a>");
return newText;
}
我有一个问题,即未正确检测到以下链接:
i对正则表达式不太好,所以请指教。
i have a problem that the following links are not detected correctly: i am not that good with regex, so please advise.
http://code.google.com/p/shindig-dnd/
http://confluence.atlassian.com/display/GADGETDEV/Gadgets+and+JIRA+Portlets
www.liferay.com/web/raymond.auge/blog /
www.liferay.com/web/raymond.auge/blog/
(www.opensocial.org/)
(www.opensocial.org/)
推荐答案
你遇到的问题是你在角色中使用 -
group( []
)没有转义它,用于定义范围 .-?
(即字符 ./ 0123456789:;< =>
?)。要么转义它 \\ -
,要么将它放在字符类的末尾,这样它就不会完成一个范围。
The problem you have is that you are using -
within a character group ([]
) without escaping it, which is being used to define the range .-?
(i.e. the characters ./0123456789:;<=>?
). Either escape it \\-
or put it at the end of the character class so that it doesn't complete a range.
public static String detectUrls(String text) {
String newText = text
.replaceAll("(?:https?|ftps?|http?)://[\\w/%.\\-?&=]+",
"<a href='$0'>$0</a>").replaceAll(
"(www\\.)[\\w/%.\\-?&=]+", "<a href='http://$0'>$0</a>");
return newText;
}
这篇关于我的正则表达式检测字符串中的URL的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!