我编写了一个程序来对发件人的通用位置进行地理定位,但是我在从字符串中提取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;
任何想法?
答案 0 :(得分: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
答案 1 :(得分:1)
与Miky类似但使用positive lookahead/behind因此我们只选择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;