我在使用正则表达式解析'ipconfig /all‘的输出时遇到了一些问题。目前我正在使用RegexBuddy进行测试,但我想在C#.NET中使用正则表达式。
我的输出是:
Ethernet adapter Yes:
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : MAC Bridge Miniport
Physical Address. . . . . . . . . : 02-1F-29-00-85-C9
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
Link-local IPv6 Address . . . . . : fe80::f980:c9c3:a574:37a%24(Preferred)
Link-local IPv6 Address . . . . . : fe80::f980:c9c3:a574:37a7%24(Preferred)
Link-local IPv6 Address . . . . . : fe80::f980:c9c3:a574:37a8%24(Preferred)
IPv4 Address. . . . . . . . . . . : 10.0.0.1(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.0.0
IPv4 Address. . . . . . . . . . . : 172.16.0.1(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 172.16.0.254
DHCPv6 IAID . . . . . . . . . . . : 520228888
DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-17-1C-CC-CF-00-1F-29-00-85-C9
DNS Servers . . . . . . . . . . . : 192.162.100.15
192.162.100.16
NetBIOS over Tcpip. . . . . . . . : Enabled到目前为止,我编写的正则表达式是:
([ -~]+):.+(?:Description\s)(?:\.|\s)+:\s([ -~]+).+(?:Physical Address)(?:\.|\s)+:\s([ -~]+).+(?:DHCP Enabled)(?:\.|\s)+:\s([ -~]+).+(?:(?:Link-local IPv6 Address)(?:\.|\s)+:\s([ -~]+).+Preferred.+)+问题是,我想要捕获所有有用的字段作为组,以便在C#中轻松获取它们,并且出于某些原因-当我捕获多个“链接本地IPv6地址”字段时,它停止工作。
如果能帮上忙我会很感激,谢谢。
编辑:另一个问题是我从远程机器接收ipconfig数据(那里有一个我无法控制的非托管程序)-因此我不能使用WMI或类似的东西以另一种方式获取ipconfig信息。
发布于 2013-03-03 19:56:47
为什么使用正则表达式?您的输入是简单的键值格式。使用类似...的东西
foreach (var line in lines)
{
var index = line.IndexOf (':') ;
if (index <= 0) continue ; // skip empty lines
var key = line.Substring (0, index).TrimEnd (' ', '.') ;
var value = line.Substring (index + 1).Replace ("(Preferred)", "").Trim () ;
}发布于 2013-03-03 18:08:01
但是我想在C#.NET中使用正则表达式。
为什么选择Regex?相信我,您不会想使用正则表达式的。一位智者曾经说过:
有些人在遇到问题时会想:“我知道,我会用正则表达式。”现在他们有两个问题。
现在让我来说明你的两个问题:
解析此工具的输出
实际上,您可以使用WMI直接检索此信息,从而解决您的原始问题,而再也不用考虑使用正则表达式:
using (var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
using (var instances = mc.GetInstances())
{
foreach (ManagementObject instance in instances)
{
if (!(bool)instance["ipEnabled"])
{
continue;
}
Console.WriteLine("{0}, {1}, {2}", instance["Caption"], instance["ServiceName"], instance["MACAddress"]);
string[] ipAddresses = (string[])instance["IPAddress"];
string[] subnets = (string[])instance["IPSubnet"];
string[] gateways = (string[])instance["DefaultIPGateway"];
string domains = (string)instance["DNSDomain"];
string description = (string)instance["Description"];
bool dhcp = (bool)instance["DHCPEnabled"];
string[] dnses = (string[])instance["DNSServerSearchOrder"];
}
}除此之外,您可以使用Mgmtclassgen.exe实用程序为这些WMI类创建强类型包装器,从而使您的代码更加安全,并且您将能够摆脱神奇的字符串。
发布于 2013-03-03 18:47:24
当然,您可以通过使用NetworkInterface.GetAllNetworkInterfaces()获得所有这些信息
https://stackoverflow.com/questions/15184495
复制相似问题