2014-01-21 44 views
3

因此,我正在C#中的一个小项目工作,并希望读取长文本文件,当它遇到该行"X-Originating-IP: [192.168.1.1]"我想抓住IP并显示到控制台只是公认的IP#,所以只是192.168.1.1等。我无法理解正则表达式。任何能够让我开始的人都会很感激。我到目前为止已经在下面。需要帮助从c#中的字符串获取IP

namespace x.Originating.Ip 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int counter = 0; 
      string line; 
      System.IO.StreamReader file = 
       new System.IO.StreamReader("C:\\example.txt"); 

      while ((line = file.ReadLine()) != null) 
      { 
       if (line.Contains("X-Originating-IP: ")) 
       Console.WriteLine(line); 
       counter++; 
      } 

      file.Close(); 
      Console.ReadLine(); 
     } 
    } 
} 
+3

在几年前,这将一直是个简单的'(\ d + \ \ d + \ \ d +。 \。\ d +)'类型的情况,但是现在你也必须处理IPv6地址,这是完全不同的球类游戏。 –

回答

4

你并不需要经常使用表情:

if (line.Contains("X-Originating-IP: ")) { 
    string ip = line.Split(':')[1].Trim(new char[] {'[', ']', ' '}); 
    Console.WriteLine(ip); 
} 
+1

+1不使用正则表达式:) – rhughes

+0

这将给出像[192.168.1.1] – DareDevil

+1

@DareDevil的输出,我更新了代码以修剪'[',']'。谢谢你指出。 – falsetru

0

我不知道,但我想你的文本文件包含一个IP地址的每一行,现在您的代码可以简化像这样如下:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Text.RegularExpressions; 


namespace x.Originating.Ip 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string[] lines = System.IO.File.ReadAllLines("Your path & filename.extension"); 
      Regex reg = new Regex("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"); 
      for (int i = 0; i < lines.Length; ++i) 
      { 
       if (reg.Match(lines[i]).Success) 
       { 
        //Do what you want........ 
       } 
      } 
     } 
    } 
} 
0

下面的正则表达式应该得到你想要的东西:

(?<=X-Originating-IP: +)((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?) 

这使用积极lookbehind来断言"X-Originating-IP: "存在后跟IPv4地址。只有IP地址将被比赛捕获。

4

试试这个例子:

//Add this namespace 
using System.Text.RegularExpressions; 

String input = @"X-Originating-IP: [192.168.1.1]"; 
Regex IPAd = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"); 
MatchCollection MatchResult = IPAd.Matches(input); 
Console.WriteLine(MatchResult[0]); 
0

而不是做一个正则表达式,它看起来像你解析MIME电子邮件,考虑LumiSoft.Net.MIME它可以让你访问的头一个定义的API。

另外,使用内置的IPAddress.Parse类,它同时支持IPv4和IPv6:

const string x_orig_ip = "X-Originating-IP:"; 
string header = "X-Originating-IP: [10.24.36.17]";  

header = header.Trim(); 
if (header.StartsWith(x_orig_ip, StringComparison.OrdinalIgnoreCase)) 
{ 
    string sIpAddress = header.Substring(x_orig_ip.Length, header.Length - x_orig_ip.Length) 
     .Trim(new char[] { ' ', '\t', '[', ']' }); 
    var ipAddress = System.Net.IPAddress.Parse(sIpAddress); 
    // do something with IP address. 
    return ipAddress.ToString(); 
}