在Java中如何检查字符串是否包含URL

4
如果我有一个如下的字符串:
String str = "Google is awesome search engine. https://www.google.co.in";

现在,我需要检查以上字符串中是否包含任何链接。由于字符串包含一个链接,因此应该返回 true。
该函数应该也检查 www.google.com 作为链接。它不应该依赖于 http:// 或 https://。
我已经检查了这个链接:What's the best way to check if a String contains a URL in Java/Android? 但是它只有在字符串仅包含 url 时才会返回 true,而我想让它在任何位置包含链接时都返回 true。
我希望也能匹配这个模式的字符串,以便我可以将其设置为 Android 中的 textview 并使其可点击。
请告诉我如何做到这一点,谢谢。

3个回答

4

{1,4}有什么用处?不能使用像ti.com这样的内容吗?如果一级域名是barcelona(它超过六个字母),会发生什么?我认为有很多有效的URL将不匹配您的正则表达式。国际化域名怎么办? - Luis Colorado

1
你可以按空格分割字符串,然后使用上面链接中提到的方法测试结果数组中的每个“单词”。
String[] words = str.split(" ");
for (String word : words) {
    // test here using your favourite methods from the linked answer
}

0
最简单的方法是使用indexOf方法。例如:
String target =" test http://www.test1.com";
String http = "http:";
System.out.println(target.indexOf(http));

或者,您可以使用正则表达式:

String target ="test http://www.test1.com";
String http = "((http:\\/\\/|https:\\/\\/)?(www.)?(([a-zA-Z0-9-]){2,}\\.){1,4}([a-zA-Z]){2,6}(\\/([a-zA-Z-_\\/\\.0-9#:?=&;,]*)?)?)";
Pattern pattern = Pattern.compile(http);
Matcher matcher = pattern.matcher(target);
while (matcher.find()) {
    System.out.println(matcher.start() + " : " + matcher.end());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接