从主机名C#提取ISP

时间:2018-11-10 08:14:02

标签: c# regex

我正在使用ipstack来获取有关用户IP的信息。它为我提供了主机名,但是我想使用该主机名来获取ISP。我得到的主机名是:

  

d9687b05.cm-24.dynamic.ziggo.nl

我想提取ziggo.nl <-就是ISP的地方。

当然,它永远不会是ziggo,也不会一直是.nl,那么我将如何在不同的主机名上使用那部分主机名?

3 个答案:

答案 0 :(得分:0)

您可以使用此正则表达式捕获最后两个单词,

const merge = (...arrs) => arrs[0].map((_, i) => (
  //                   Extract the [i]th item from every array:
  Object.assign({}, ...arrs.map(arr => arr[i]))
));

const one = [
  { id: 1, title: 'One' },
  { id: 2, title: 'Two' }
];
const two = [
  { status: 'Open' },
  { status: 'Close' }
];
const three = [
  { items: 10 },
  { items: 2 }
];

console.log(merge(one, two));
console.log(merge(one, two, three));

Demo

说明:

  • .*\.(\w+\.\w+) ->匹配零个或多个任意字符,后跟一个文字点
  • .*\.->匹配一个或多个单词char,后跟文字点,再匹配一个或多个单词char

这是示例C#代码,

(\w+\.\w+)

这将提供以下输出,

    public static void Main(string[] args)
    {
        var pattern = ".*\\.(\\w+\\.\\w+)";
        var match = Regex.Match("d9687b05.cm-24.dynamic.ziggo.nl", pattern);
        Console.WriteLine("DomainName: " + match.Groups[1].Value);
    }

答案 1 :(得分:0)

代替使用正则表达式,我将执行以下操作:

string isp = "";
string[] split = hostname.Split('.');
int len = split.Length;
if(len >= 2)
   isp = $"{split[len-2]}.{split[len-1]}";

或者这个:

    string isp = "";
    string hostname = "d9687b05.cm-24.dynamic.ziggo.nl";
    int a = hostname.LastIndexOf(".");
    if(a>0)a=hostname.LastIndexOf(".", a-1);
    if(a!=-1) isp = hostname.Substring(a+1);

Live Demo

答案 2 :(得分:0)

没有正则表达式和额外的解释,就可以用易于理解的方式完成;)

var names = hostname.split(".");
var notRequired = Math.Max(0, names.Count() - 2);

var isp = string.Join(".", names.skip(notRequired));