What's the best way to check if a String contains a URL in Java/Android?

前端 未结 10 1277
轮回少年
轮回少年 2020-12-02 21:18

What\'s the best way to check if a String contains a URL in Java/Android? Would the best way be to check if the string contains |.com | .net | .org | .info | .everythingelse

10条回答
  •  一个人的身影
    2020-12-02 21:23

    After looking around I tried to improve Zaid's answer by removing the try-catch block. Also, this solution recognizes more patterns as it uses a regex.

    So, firstly get this pattern:

    // Pattern for recognizing a URL, based off RFC 3986
    private static final Pattern urlPattern = Pattern.compile(
        "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
                + "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
                + "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
        Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    

    Then, use this method (supposing str is your string):

        // separate input by spaces ( URLs don't have spaces )
        String [] parts = str.split("\\s+");
    
        // get every part
        for( String item : parts ) {
            if(urlPattern.matcher(item).matches()) { 
                //it's a good url
                System.out.print(""+ item + " " );                
            } else {
               // it isn't a url
                System.out.print(item + " ");    
            }
        }
    

提交回复
热议问题