Parsing result of URL.getHost()

前端 未结 2 1877
天涯浪人
天涯浪人 2021-01-19 19:16

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 retur

相关标签:
2条回答
  • 2021-01-19 20:05
    String host = url.getHost();
    Matcher m = Pattern.compile("^.+[.]([^.]+[.][^.]+)$").matcher(host);
    if(m.matches()) {
      host = m.group(1);
    }
    
    0 讨论(0)
  • 2021-01-19 20:10

    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);
    }
    
    0 讨论(0)
提交回复
热议问题