这并没有为我工作。我想出了这些方法,假设主机名和端口总是通过冒号连接在一起。这个假设适用于我在工作中需要处理的所有数据库(Oracle,Vertica,MySQL等)。但它可能不适用于不能连接到网络端口的东西。
String url = null; // set elsewhere in the class
final public String regexForHostAndPort = "[.\\w]+:\\d+";
final public Pattern hostAndPortPattern = Pattern.compile(regexForHostAndPort);
public String getHostFromUrl() {
Matcher matcher = hostAndPortPattern.matcher(url);
matcher.find();
int start = matcher.start();
int end = matcher.end();
if(start >= 0 && end >= 0) {
String hostAndPort = url.substring(start, end);
String [] array = hostAndPort.split(":");
if(array.length >= 2)
return array[0];
}
throw new IllegalArgumentException("couldn't find pattern '" + regexForHostAndPort + "' in '" + url + "'");
}
public int getPortFromUrl() {
Matcher matcher = hostAndPortPattern.matcher(url);
matcher.find();
int start = matcher.start();
int end = matcher.end();
if(start >= 0 && end >= 0) {
String hostAndPort = url.substring(start, end);
String [] array = hostAndPort.split(":");
if(array.length >= 2)
return Integer.parseInt(array[1]);
}
throw new IllegalArgumentException("couldn't find pattern '" + regexForHostAndPort + "' in '" + url + "'");
}