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

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

    The best way is to to set the property autolink to your textview, Android will recognize, change the appearance and make clickable a link anywhere inside the string.

    android:autoLink="web"

    0 讨论(0)
  • 2020-12-02 21:38

    This is simply done with a try catch around the constructor (this is necessary either way).

    String inputUrl = getInput();
    if (!inputUrl.contains("http://"))
        inputUrl = "http://" + inputUrl;
    
    URL url;
    try {
        url = new URL(inputUrl);
    } catch (MalformedURLException e) {
        Log.v("myApp", "bad url entered");
    }
    if (url == null)
        userEnteredBadUrl();
    else
        continue();
    
    0 讨论(0)
  • 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");
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题