[英]parse regex from array
我正在嘗試從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;
}
}
}
有什么幫助或建議嗎?
將您的#
更改為\\d
:
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])
IPAddress.Parse方法不會重新發明輪子。
如果您要匹配IPv4,請嘗試使用此野獸,它應與實際的IPv4相當接近, \\ b表示單詞的開頭和結尾,因此您應該能夠刪除它們並進行調整根據您的標題格式獲取您的心臟內容
\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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.