【问题标题】:How to check if a string contains url in java如何在java中检查字符串是否包含url
【发布时间】:2015-12-07 13:26:47
【问题描述】:

如果我有如下字符串:

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 中设置它并使其可点击。

我该怎么做,请帮帮我。

【问题讨论】:

标签: java regex string


【解决方案1】:

正则表达式是

((http:\/\/|https:\/\/)?(www.)?(([a-zA-Z0-9-]){2,}\.){1,4}([a-zA-Z]){2,6}(\/([a-zA-Z-_\/\.0-9#:?=&;,]*)?)?)

Check this link for more information

【讨论】:

  • 那里{1,4} 有什么用,你不能有ti.com 之类的东西吗,一级域barcelona 会发生什么(它有六个以上的字母)?我认为有很多有效的网址与您的正则表达式不匹配。国际化域名呢?
【解决方案2】:

您可以将字符串拆分为空格,然后使用the answer you linked to above 中的一种方法测试结果数组中的每个“单词”。

String[] words = str.split(" ");
for (String word : words) {
    // test here using your favourite methods from the linked answer
}

【讨论】:

    【解决方案3】:

    最简单的方法是使用 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());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 2011-08-13
      • 2017-09-23
      相关资源
      最近更新 更多