-5

我编写了一个程序来地理定位发件人的通用位置,但是我在从字符串中提取 IP 地址时遇到问题,例如:

   public static string getBetween(string strSource, string strStart, string strEnd)
    {
        int Start, End;
        if (strSource.Contains(strStart) && strSource.Contains(strEnd))
        {
            Start = strSource.IndexOf(strStart, 0) + strStart.Length;
            End = strSource.IndexOf(strEnd, Start);
            return strSource.Substring(Start, End - Start);
        }
        else
        {
            return "";
        }

// 我已经将完整的 EMAIL 的 MIME 数据捕获到一个字符串 (txtEmail) // 现在我搜索字符串 ...

  //THIS IS MY PROBLEM. this is always different. 
  // I need to capture only the IP address between the brackets
  string findIP = "X-Originating-IP: [XXX.XXX.XXX.XXX]"; 
  string data = getBetween(findIP, "[", "]");
  txtCustomIPAddress.Text = data;

有任何想法吗?

4

2 回答 2

1

我会建议一个正则表达式

Regex rex = new Regex("X-Originating-IP\\:\\s*\\[(.*)\\]", RegexOptions.Multiline|RegexOptions.Singleline);

string ipAddrText = string.Empty;
Match m = rex.Match(headersText);
if (m.Success){
    ipAddrText = m.Groups[1].Value;
}

// ipAddrText should contain the extracted IP address here

工作演示在这里

于 2013-03-14T14:10:19.870 回答
1

与 Miky 类似,但使用正向前瞻/后向,因此我们只选择 IP 地址。

var str = "X-Originating-IP: [XXX.XXX.XXX.XXX]";
var m = Regex.Match(str, @"(?<=X-Originating-IP:\ \[).*?(?=])");
var ipStr = m.Success ? m.Value : null;
于 2013-03-14T14:17:26.490 回答