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

前端 未结 10 1275
轮回少年
轮回少年 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:41

    Best way would be to use regular expression, something like below:

    public static final String URL_REGEX = "^((https?|ftp)://|(www|ftp)\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$";
    
    Pattern p = Pattern.compile(URL_REGEX);
    Matcher m = p.matcher("example.com");//replace with string to compare
    if(m.find()) {
        System.out.println("String contains URL");
    }
    

提交回复
热议问题