I have a need to get hostname in httpd url. So. I made it simple by using pattern and matcher class.


public class Util {
public synchronized static String getHost(String domainURL) {
String host = new String();
Pattern pattern = Pattern.compile("(http://)+(\\w++-?\\w++)|(\\w++).?(\\w++.)++(\\w++)");
Matcher match = pattern.matcher(domainURL);
while (match.find()) {
String dashContained = match.group(2);
if (dashContained != null) {
host = match.group(2);
} else {
host = match.group(3);
}
}
return host;
}
}




public class GettingHostTest {
@Test
public void getHost() {
String url = "http://gmail.google.com"; // fulll domain
String host = MonitorUtil.getHost(url);
Assert.assertEndsWith("gmail", host);
}
@Test
public void getHost1() {
String url = "http://gmail1568h125.svr.google.com"; // sub domain
String host = MonitorUtil.getHost(url);
Assert.assertEndsWith("gmail1568h125", host);
}
@Test
public void getHost2() throws Exception {
String url = "http://alpha-gmail.google.com"; // dash contained domain
String host = MonitorUtil.getHost(url);
Assert.assertEndsWith("alpha-gmail", host);
}
}


'java core' 카테고리의 다른 글

Rounding(Scaling) x postion of decimal point  (0) 2009.04.29
How to get cpu usage in java.  (0) 2009.04.29
G1 garbage collection  (0) 2009.04.28
Implementing equals method of collections classes  (0) 2009.04.27
JavaOne 2008  (0) 2009.04.17
Posted by '김용환'
,