【问题标题】:Extract complete url from a text in android从android中的文本中提取完整的url
【发布时间】:2015-11-26 11:19:45
【问题描述】:

我想从大文本中提取完整的url,这样就需要提取包含参数的完整url。

应该支持所有的url格式...

例如网址

  1. www.facebook.com/mainhoon/jikii/50
  2. http://www.alphabet.com?user=50&tyn=40
  3. m.gmail.com 等等

例如文本:

你好,你好,你看看我的代码http://www.stackoverflow.com?adiadajda 在这里我们得到了答案,还检查了这个网址 www.myspace.in,它给出了 bla bla bla

【问题讨论】:

  • 添加包含 URL 的示例内容

标签: regex string url


【解决方案1】:

您尝试从文本中解析整个字符串,然后比较每个字符串以匹配 url。如果该字符串具有 url 模式,则该字符串是一个完整的 url。

例如。嗨,这是我的 fb 个人资料 www.facebook.com/prasilabs 检查一下。

在该示例中,如果我们获取所有字符串并检查 url 模式,我们将获得 url www.facebook.com/prasilabs

public static List<String> extractUrls(String input)
{
    List<String> result = new ArrayList<String>();

    String[] words = input.split("\\s+");


    Pattern pattern = Patterns.WEB_URL;
    for(String word : words)
    {
        if(pattern.matcher(word).find())
        {
            if(!word.toLowerCase().contains("http://") && !word.toLowerCase().contains("https://"))
            {
                word = "http://" + word;
            }
            result.add(word);
        }
    }

    return result;
}

【讨论】:

  • 应该是这个if(word.toLowerCase().contains("http://") || word.toLowerCase().contains("https://")) { }else word = "https://" + word;
【解决方案2】:

通过 Kotlin 提取单个 url

private fun extractUrl(input: String) =
        input
            .split(" ")
            .firstOrNull { Patterns.WEB_URL.matcher(it).find() }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多