判断扫描后的内容是否是URL

来源:互联网 发布:淘宝优惠券查询 编辑:程序博客网 时间:2024/05/03 09:57


扫描的明明是Url,居然当文本给处理了,看来正则没有通过。





扫描二维码后,我参考了QQ的效果,分了三种:网页地址,文件下载地址,文本信息;为了实现这种效果,我

发现有很多url很奇葩。所以就想找找别人是怎么用正则来过滤url的。后来我在网上找到了两种实现的正则表达

式,但是都不满足我们的要求。下面贴出网上找的正则:


第一种:


    public static boolean isUrl(String str) {        String regex = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- .%&=]*)?";        return Pattern.compile(regex).matcher(str).matches();    }



第二种:


    public static boolean isUrl(String str) {        // 转换为小写        str = str.toLowerCase();        String domainRules = "com.cn|net.cn|org.cn|gov.cn|com.hk|com|net|org|int|edu|gov|mil|arpa|Asia|biz|info|name|pro|coop|aero|museum|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cf|cg|ch|ci|ck|cl|cm|cn|co|cq|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|es|et|ev|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gp|gr|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|ml|mm|mn|mo|mp|mq|mr|ms|mt|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|va|vc|ve|vg|vn|vu|wf|ws|ye|yu|za|zm|zr|zw";        String regex = "^((https|http|ftp|rtsp|mms)?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // ftp的user@                + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184                + "|" // 允许IP和DOMAIN(域名)                + "(([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]+\\.)?" // 域名- www.                + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名                + "(" + domainRules + "))" // first level domain- .com or                // .museum                + "(:[0-9]{1,4})?" // 端口- :80                + "((/?)|" // a slash isn't required if there is no file name                + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";        Pattern pattern = Pattern.compile(regex);        Matcher isUrl = pattern.matcher(str);        return isUrl.matches();    }


现在我有四个url,当然不是正规的,因为我这是为了满足我们的要求而做的:


String url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.ishangbin.user";//APP在应用宝的下载地


址,生成二维码后扫描跳到下载页面


        String url1 = "http://www.baidu.cn/download?t=“test”&v=7616";//随便弄的页面


        String url2 = "https://";//测试用的


String url3 = "http://www.baidu.com";



检验方法一:





检验方法二:





看来这两种方法,不能兼容我们的要求。只能自己来改造了。但是我又不会正则,那就只能自己写java代

码来实现了:


然后自己就写了几行代码:


   public static boolean isUrl(String str) {        // 转换为小写        str = str.toLowerCase();        String[] regex = { "http://", "https://" };        boolean isUrl = false;        for (int i = 0; i < regex.length; i++) {            isUrl = isUrl || (str.contains(regex[i])) && str.indexOf(regex[i]) == 0;        }        return isUrl;    }



一运行:当当当当。。。






全部通过!!!目的达到了,然后再放进项目运行一下:



0 0