检查是否字符串是Android上的网址或IP [英] Checking if string is web address or ip on android

查看:698
本文介绍了检查是否字符串是Android上的网址或IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证,如果在文本编辑输入的字符串是一个网络地址,如: www.stackoverflow.com或IP地址如。 64.34.119.12。我已经试过这两种方法都没有成功。我有私人命名的IP类变量。

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.

方法1:

public boolean isAdress(){

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

方法2是一个被我把它发送到NetTask前检查字符串。

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;
    }

这第二种方法也没有wotk,但即使那样,它不会是能够验证网络ADRESS。

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?

编辑:
阅读正则表达式之后我试过这种方法也:

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;
    }           
    }

但它似乎返回false所有的时间。

but it seems to return false all the time.

推荐答案

简短的回答:尝试使用正则表达式

Short answer: Try using regex!

编辑:

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

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

如果你谷歌你可以找到IP地址,正确的正则表达式的字符串和URL ...

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

请注意:
一种正则表达式的URL可以是你想要的东西不同,你只需要HTTP:// https://或所有有效的网址(例如市场://)...

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

这篇关于检查是否字符串是Android上的网址或IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆