当前位置: 代码迷 >> C# >> 使用正则表达式可否将windows中hosts文件中的内容拆分成key、value的形式
  详细解决方案

使用正则表达式可否将windows中hosts文件中的内容拆分成key、value的形式

热度:175   发布时间:2016-05-05 05:16:25.0
使用正则表达式能否将windows中hosts文件中的内容拆分成key、value的形式?
例如一个是这样的一个内容:
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
# localhost name resolution is handled within DNS itself.
# 127.0.0.1       localhost
# ::1             localhost
127.0.0.1          test.x.cn
#127.0.0.1     test1.x.cn
#127.0.0.1          test2.x.cn
#127.0.0.1          test3.x.cn

所获取的key、value结果集应该是这样:

key                   value
#127.0.0.1            localhost
127.0.0.1             test.x.cn
#127.0.0.1            test1.x.cn
#127.0.0.1            test2.x.cn
#127.0.0.1            test3.x.cn

也就是值获包含IP地址的每一行(注释掉的也算)
------解决思路----------------------
这。。。杀鸡焉用牛刀。
直接split就OK了
            string path=@"C:\hosts.ini";
            string[] lines = System.IO.File.ReadAllLines(path, Encoding.Default);
            foreach(string line in lines)
            {
                string[] strs = line.Split('"/^\s*$/"); //以空格分割,包括多个空格。用正则表达式实现的,原谅我不会正则
                string name = strs[0].Trim();
                string value = strs[1].Trim();
                Console.WriteLine("键是:{0},值是:{1}", name, value);
            }

------解决思路----------------------
split或者正则都ok
------解决思路----------------------
正则:
(?<ip>#?(\d{1,3}.){3}\d{1,3})\s+?(?<host>\S+)

构造正则参数里要选上 mulitline和signline;然后用Matchs匹配,然后每项匹配得到的捕获组 xxx.Groups["ip"].Value就是前面的ip,["host"].Value就是后面的域名
------解决思路----------------------
string path=@"C:\Windows\System32\drivers\etc\hosts";
string[] lines = File.ReadAllLines(path);
IEnumerable<string[]> lineDic = lines.Select(l => l.Split(' ').Select(w => w.Trim()).Where(q => !String.IsNullOrEmpty(q)))
    .Where(e => e.Count() == 2).Select(r => r.ToArray());
foreach (string[] line in lineDic)
{
    Console.WriteLine("键是:{0},值是:{1}", line[0], line[1]);
}


或者可以这样
  相关解决方案