Parsing result of URL.getHost()
Need help parsing...
In my code, I have a method that returns url.getHost();. But the results of that can be blarg.com, or sometimes dates.blarg.com. I want to return blarg.com for either situation (or for xxx.yyy.ggg.blarg.com).
I can I accompl开发者_开发百科ish this?
Thanks!
EDIT: getHost() is from java's built in class java.net.URL.
String host = url.getHost();
Matcher m = Pattern.compile("^.+[.]([^.]+[.][^.]+)$").matcher(host);
if(m.matches()) {
host = m.group(1);
}
Using split:
String host = url.getHost();
String[] items = host.split("\\.");
if(items.length>2)
host = items[items.length-2] + '.' + items[items.length-1];
Using indexes:
String host = url.getHost();
while(host.indexOf('.')!=host.lastIndexOf('.')) {
host = host.substring(host.indexOf('.') + 1);
}
精彩评论