代码:
public class DomainUrlUtils {
private static String[] TLD = {"com", "net"};
private static String[] SLD = {"co\\.kr"};
public static String getDomainName(String url) {
Pattern pattern = Pattern.compile("(?<=)[^(\\.|\\/)]\\w+\\.(" + joinTldAndSld("|") + ")$");
Matcher match = pattern.matcher(url);
String domain = null;
if (match.find()) {
domain = match.group();
}
return domain;
}
private static String joinTldAndSld(String delimiter) {
String t = String.join(delimiter, TLD);
String s = String.join(delimiter, SLD);
return new StringBuilder(t).append(s.isEmpty() ? "" : "|" + s).toString();
}
}
测试:
public class DomainUrlUtilsTest {
@Test
public void getDomainName() throws Exception {
String[][] domainUrls = {
{
"test.com",
"sub1.test.com",
"sub1.sub2.test.com",
"https://sub1.test.com",
"http://sub1.sub2.test.com"
},
{
"https://domain.com",
"https://sub.domain.com"
},
{
"http://domain.co.kr",
"http://sub.domain.co.kr",
"http://local.sub.domain.co.kr",
"http://local-test.sub.domain.co.kr",
"sub.domain.co.kr",
"domain.co.kr",
"test.sub.domain.co.kr"
}
};
String[] expectedUrls = {
"test.com",
"domain.com",
"domain.co.kr"
};
for (int domainIndex = 0; domainIndex < domainUrls.length; domainIndex++) {
for (String url : domainUrls[domainIndex]) {
String convertedUrl = DomainUrlUtils.getDomainName(url);
if (expectedUrls[domainIndex].equals(convertedUrl)) {
System.out.println(url + " -> " + convertedUrl);
} else {
Assert.fail("origin Url: " + url + " / converted Url: " + convertedUrl);
}
}
}
}
}
结果:
test.com -> test.com
sub1.test.com -> test.com
sub1.sub2.test.com -> test.com
https://sub1.test.com -> test.com
http://sub1.sub2.test.com -> test.com
https://domain.com -> domain.com
https://sub.domain.com -> domain.com
http://domain.co.kr -> domain.co.kr
http://sub.domain.co.kr -> domain.co.kr
http://local.sub.domain.co.kr -> domain.co.kr
http://local-test.sub.domain.co.kr -> domain.co.kr
sub.domain.co.kr -> domain.co.kr