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

前端 未结 10 1262
轮回少年
轮回少年 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条回答
  •  Happy的楠姐
    2020-12-02 21:45

    This function is working for me

    private boolean containsURL(String content){
        String REGEX = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        Pattern p = Pattern.compile(REGEX,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(content);
        if(m.find()) {
            return true;
        }
    
        return false;
    }
    

    Call this function

    boolean isContain = containsURL("Pass your string here...");
    Log.d("Result", String.valueOf(isContain));
    

    NOTE :- I have tested string containing single url

提交回复
热议问题