2

嘿,我正在尝试基于什么是检查字符串是否为有效 URL 的最佳正则表达式的 url 验证?在java中,但由于某种原因它不起作用。建议?

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class urlValidate {

    /**
     * @param args
     */
    public static void main(String[] args) {
        test_url("http://brb/", false);
            test_url("https://localserver/projects/public/assets/javascript/widgets/UserBoxMenu/widget.css", false);
    test_url("https://www.google.com/", true);
    test_url("https://www.google.co.uk/projects/my%20folder/test.php", false);
    test_url("https://myserver.localdomain/", true);
    test_url("https://192.168.1.120/projects/index.php/", false);
    test_url("https://192.168.1.1/", true);
    test_url("https://projectpier-server.localdomain/projects/public/assets/javascript/widgets/UserBoxMenu/widget.css", false);
    test_url("https://2.4.168.19/project-pier?c=test&a=b", false);
    test_url("https://localhost/a/b/c/test.php?c=controller&arg1=20&arg2=20", false);
    test_url("https://user:password@localhost/a/b/c/test.php?c=controller&arg1=20&arg2=20", false);
    test_url("myserver",false);
    test_url("https://tomcat:8080/",true);
    test_url("https://facebook.com",false);
}

public static void test_url(String url, boolean expected) {
    boolean valid = isURLValid(url, true);
    String out = "URL Valid?: " + (valid ? "yes" : "no") + " for URL: "
            + url + ". Expected: " + (expected ? "yes" : "no") + ". ";
    if (valid == expected) {
        out += "PASS\n";
    } else {
        out += "FAIL\n";
    }
    System.out.println(out);
}

public static boolean isURLValid(String url, boolean forcehttps) {
    String regex = "";
    if (forcehttps) {
        regex = "/^(https):\\/\\/";
    } else {
        regex = "/^(https?):\\/\\/";
    }
    regex += "((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*"
            + "[a-z][a-z0-9-]*[a-z0-9]"
            + "|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}"
            + "(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])"
            + ")(:\\d+)?)"
            + "(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?(\\/)"
            + "$/i";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(url); // get a matcher object
    return m.matches();
}

}
4

3 回答 3

2

正则表达式最初用斜杠包裹(用作分隔符,这是 PHP 中 PCRE 所必需的)。Java 不使用这些。

if (forcehttps) {
    regex = "^(https):\\/\\";
} else {
    regex = "^(https?):\\/\\";
}

最后/i也是不可取的。相反,写

Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE)
于 2013-02-21T18:25:48.993 回答
1

您可以使用 Apache commons-validator api。有一个名为UrlValidator的类,或者类似的东西。
看看这个:http
: //commons.apache.org/validator/ 我不懂很多正则表达式,所以在这个主题上我帮不了你太多。
祝你好运。

于 2013-02-21T18:27:30.470 回答
0

虽然将正则表达式写入 URL 验证不是问题,但为什么不直接使用java.io.URL类呢?只需创建URL如下实例:如果语法错误new URL(spec),它将抛出。MalformedURLExcption

于 2013-02-21T18:30:21.660 回答