Checking if string is web address or ip on android

北战南征 提交于 2019-12-24 05:31:25

问题


I need to validate if string entered in TextEdit is a web address eg. "www.stackoverflow.com" or an ip address eg. "64.34.119.12". I have tried this two methods without success. I have private class variable named ip.

Method 1:

public boolean isAdress(){

        boolean isaddr = true;
        try
        {
            ip = new NetTask().execute(""+textEdit1.getText()).get();
        }
        catch (Exception ex)
        {
            isaddr = false;
        }
        return isaddr;
    }

Method 2 is the one were I check string before sending it to NetTask.

public boolean isAdress(){
        String adress = textEdit1.getText().toString();
        boolean isaddr = true;
        if (adress.length() > 0) {
            String[] nums = adress.split(".");
            if (nums.length == 4) {
                for (String str : nums) {
                    int i = Integer.parseInt(str);
                    if ((i < 0) || (i > 255)) {
                        isaddr = false;
                    }
                }
            } 
        }
        return isaddr;
    }

this second method also doesn't wotk, but even if it did, it wouldn't be able to validate web adress.

So it there any way I can validate string for both of this cases?

EDIT: After reading about regex I tried this method also:

private String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

public boolean isAdress(){
        String adress = textEdit1.getText().toString();
        try {
            Pattern patt = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
            Matcher matcher = patt.matcher(adress);
            return matcher.matches();
        } catch (RuntimeException e) {
        return false;
    }           
    }

but it seems to return false all the time.


回答1:


Short answer: Try using regex!

EDIT:

if(textEdit1.getText().matches(REGEX_URL)) {
    //DO URL THINGS
}

if(textEdit1.getText().matches(REGEX_IPADDRES)) {
    //DO IP THINGS
}

If you google you can find the correct REGEX strings for IP addresses and urls...

NOTE: A regex for urls can be different for what you want, do you only want http:// https:// or all valid urls (like market://)...




回答2:


Patterns.IP_ADDRESS.matcher(url).matches();




回答3:


how about simpler approach? detect if it is IP address, e.g.

public static boolean isIP(String input) {

        if (input.contains(".") && input.length()>1) {
            return TextUtils.isDigitsOnly( input.replace(".", "").trim() );
        }
        else {
            return false;
        }
    }


来源:https://stackoverflow.com/questions/11723184/checking-if-string-is-web-address-or-ip-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!