0

我正在尝试从 Outlook 电子邮件标头中解析出 IP 地址。我已经开始用 C# 编写一些东西(因为那是我正在利用的示例)并且想出了一些接近的东西。

我可以使用字符串 lines[] = Regex.Split(headers, @"\r\n"); 拆分标题 命令没问题,但是当我尝试遍历 lines[] 数组时,我的 IP 地址正则表达式失败并且不会将值存储在第二个数组中:

代码:

private void button1_Click(object sender, EventArgs e)
    {
        // use a string constant to define the mapi property
        string PidTagTransportMessageHeaders = @"http://schemas.microsoft.com/mapi/proptag/0x007D001E";
        string mypattern = @"(#{1,3}\.)(#{1,3}\.)([0-9]{1,3}\.)([0-9]{1,3})";
        // string[] ip = Regex.Split(lines[i], (@"(\(|\[)(#{1,3}\.)(#{1,3}\.)([0-9]{1,3}\.)([0-9]{1,3})(\)|\])"));

        // get a handle on the current message
        Outlook.MailItem message = (Outlook.MailItem)this.OutlookItem;

        // use the property accessor to retreive the header
        string headers = string.Empty;

        try
        {
            headers = (string)message.PropertyAccessor.GetProperty(PidTagTransportMessageHeaders);
        }
        catch { 
        }

        //  if getting the internet headers is successful, put into textbox
        string[] lines = Regex.Split(headers, "\r\n");

        Regex regexObj = new Regex(mypattern);

        for (int i = 0; i < lines.Length; i++)
        {
            MatchCollection matches = regexObj.Matches(lines[i]);                       

        }            
        //eventually write the found IP array into textBox1.Text
       textBox1.Text = headers;
        }
    }
}

有什么帮助或建议吗?

4

3 回答 3

1

将您的 's 更改#\d's:

string mypattern = @"(\d{1,3}\.)(\d{1,3}\.)(\d{1,3}\.)(\d{1,3})";

请注意,更准确的 IPv4 地址捕获正则表达式类似于:

\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b

...或者至少添加单词边界...

\b(\d{1,3}\.)(\d{1,3}\.)(\d{1,3}\.)(\d{1,3})\b

对于一个简单的 IPv6(标准),我喜欢:

(?<![:.\w])(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}(?![:.\w])
于 2012-08-08T19:06:05.327 回答
0

IPAddress.Parse 方法不要重新发明轮子。

于 2012-08-08T19:16:51.743 回答
0

如果你想匹配 IPv4,那么试试这个野兽,应该非常接近实际的 IPv4,封闭的\b表示单词的开头和结尾,所以你应该能够删除这些并调整为根据您的标头格式获取IP的您的心脏内容

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
于 2012-08-08T19:41:06.013 回答