我想使用正则表达式从文本文件中仅提取IP地址。
Interface: 192.168.8.100 --- 0x11
Internet Address Physical Address Type
192.168.8.1 a8-7d-12-c6-73-2c dynamic
192.168.8.255 ff-ff-ff-ff-ff-ff static
224.0.0.22 01-00-5e-00-00-16 static
224.0.0.251 01-00-5e-00-00-fb static
224.0.0.252 01-00-5e-00-00-fc static
239.255.102.18 01-00-5e-7f-66-12 static
239.255.255.250 01-00-5e-7f-ff-f1 static
255.255.255.255 ff-ff-ff-ff-ff-ff static
例如,在这张照片中,我只想要与此字符串匹配的IP地址192.168。等等。并希望将每个匹配项保存在单独的变量中。
string path = @"C:\Test\Result.txt";
StringBuilder buffer = new StringBuilder();
using (var sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
if (Regex.IsMatch(sr.ReadLine(), "192"))
buffer.Append(sr.ReadLine());
}
}
Console.WriteLine(buffer.ToString());
我尝试过此代码,但结果不是很令人信服。
同样,我们可以看到这部分代码并未提供所有匹配项。
我也尝试过此代码
// Spilt a string on alphabetic character
string azpattern = "[a-z]+";
string str ="192.168.1.1 tst sysy 192.168.3.1";
string[] result = Regex.Split(str, azpattern, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(500));
for (int i = 0; i < result.Length; i++)
{
Console.Write("{0}", result[i]);
if (i < result.Length - 1)
Console.Write("\n");
}
但是输入为我造成了问题。我不知道如何使用文本文件作为输入。同样,结果再次不是很令人信服。
无论如何,有人可以帮助我以这种形式获得结果吗?
String IP1 = 192.168.0.1;
String IP2 = 192.168.0.2;
依此类推,直到文件中没有其他192....。如果我们在阅读时跳过前三行,因为在我的情况下它们是无用的,那也很棒。
我认为这应该足够了:
const string ipPattern = @"^\s*(192\.168\.\d{1,3}\.\d{1,3}\b)";
var ipRegex = new Regex(ipPattern);
var ipAddresses192168 = File.ReadAllLines(@"C:\Test\Result.txt")
.Skip(3) // Skip 3 lines
.Where(line => ipRegex.IsMatch(line))
.Select(line => ipRegex.Match(line).Groups[1].Value);
foreach (var ipAddress in ipAddresses192168)
{
Console.WriteLine(ipAddress);
}
[它仅提取以192.168
开头的IP地址,并跳过前三行。