在上面的图片中,在控制台窗口中我有两个硬件地址和两个ip地址,但是datagrid只显示最后的结果,这就是为什么datagrid会跳过一个结果的原因?
代码是:
C#:
public class IPMAC
{
public string ip { get; set; }
public string mac { get; set; }
}
public ObservableCollection<IPMAC> ipmac { get; set; }
public MainWindow()
{
InitializeComponent();
ipmac = new ObservableCollection<IPMAC>();
this.DataContext = this;
}
var item = new IPMAC();
string pattern = @"(F8-F7-D3-00\S+)";
MatchCollection matches = Regex.Matches(stringData, pattern);
foreach (Match match in matches)
{
Console.WriteLine("Hardware Address : {0}", match.Groups[1].Value);
// ipmac.Add(new IPMAC() { mac = match.Groups[1].Value });
item.mac = match.Groups[1].Value;
}
// ipmac.Add(item);
string pattern2 = @"(192.168.1\S+)";
MatchCollection matchesIP = Regex.Matches(stringData, pattern2);
foreach (Match match in matchesIP)
{
Console.WriteLine("IP Address : {0}", match.Groups[1].Value);
// ipmac.Add(new IPMAC() { ip = match.Groups[1].Value });
item.ip = match.Groups[1].Value;
}
ipmac.Add(item);
}
private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
dg.ItemsSource = ipmac;
}
XAML是:
<DataGrid
Name="dg"
Grid.Row="0"
Height="250"
ItemsSource="{Binding ipmac}"
AutoGenerateColumns="False"
IsReadOnly="True"
>
<DataGrid.Columns>
<DataGridTextColumn Header="Mac Addresses" Binding="{Binding Path=mac}" />
<DataGridTextColumn Header="IP Addresses" Binding="{Binding Path=ip}"/>
</DataGrid.Columns>
</DataGrid>
答案 0 :(得分:1)
您的问题如下:您使用的字符串在其中包含此部分:
...
Hardware Address : F8- ...
Hardware Address : F8- ...
IP Address : 192...
IP Address : 192...
...
当你解析字符串(stringData
)时,你只考虑一个匹配(最后一个)。
修复如下:
string pattern = @"(F8-F7-D3-00\S+)";
Match match = Regex.Match(stringData, pattern);
string pattern2 = @"(192.168.1\S+)";
Match matchIP = Regex.Match(stringData, pattern2);
while (match.Success && matchIp.Success)
{
var item = new IPMAC();
item.mac = match.Value;
item.ip = matchIP.Value;
ipmac.Add(item);
match= match.NextMatch();
matchIp = matchIp.NextMatch();
}
当然,只有两种模式的匹配数完全相同时,此代码才有效。