我正在编写使用Regex验证URL的程序。但是当我针对这个URL测试它时(http://www.xml.com/pub/a/2003/09/17/stax.html#id=_hbc) 它失败了。任何人都可以告诉我为什么它无法匹配该URL? 这是代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPURLValidator {
private Pattern patternHost;
private Matcher matcher;
private static final String hostName = "^((https?)://)([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9]\\.)*([0-9]*\\_[0-9]*\\_" +
"[a-zA-Z0-9\\_]*)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9]){2}" +
"([0-9]*)?(\\/[\\+~%\\/\\.\\w\\-]*)?\\??([\\-\\+=&;%@\\/%\\.\\w]*)" +
"#?([\\-\\+=&;%@\\/%\\.\\w]*)$";
public IPURLValidator() {
patternHost = Pattern.compile(hostName, Pattern.CASE_INSENSITIVE);
}
public boolean validateHost(String host) {
matcher = patternHost.matcher(host);
if (matcher.find()) {
String HostName = matcher.group(0);
System.out.println(HostName);
}
return matcher.matches();
}
public static void main(String[] args) {
if (ip.validateHost("http://www.xml.com/pub/a/2003/09/17/stax.html#id=abc")) {
System.out.println("its valide host");
else {
System.out.println("its not valide URL/IP address");
}
}
}
答案 0 :(得分:0)
我想你想这样做:
public boolean validateHost(String host){
matcher = patternHost.matcher(host);
if (matcher.matches()) {
String HostName = matcher.group(0);
System.out.println(HostName);
return true;
}
return false;
}