URL 验证 无协议

Sat*_*rma 4 java url

我在 java 中使用 URLValidator 类来验证 URL 。但我希望如果用户不会在 URL 中提供任何协议,那么验证也应该返回为有效。

正确解释:如果在 URL "http://www.google.com" 中提供了它,那么它也应该是一个有效的 URL,如果提供了 "www.google.com",那么验证也应该作为有效的 URL 返回。

我已经尝试了很多。请帮助我。提前致谢。

The*_*eHe 5

检查这是否适合您:

boolean foundMatch = false;
try {
    Pattern regex = Pattern.compile("\\b(?:(https?|ftp|file)://|www\\.)?[-A-Z0-9+&#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]\\.[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
    Matcher regexMatcher = regex.matcher(subjectString);
    foundMatch = regexMatcher.matches();
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}
Run Code Online (Sandbox Code Playgroud)