[英]Trying to extract information from an email with .NET regex
我正在嘗試在股票促銷“ tout”電子郵件的“免責聲明”區域(部分垃圾郵件)中提取一些信息。
通常,兜售者將對以下內容免責:
XYZ公司已獲得為期兩周的ABC股票促銷的五萬美元補償。
我有一個正則表達式適用於這種情況(按目前的情況來看可能不是最有效的),並且它似乎適用於大多數情況。 但是,當免責聲明使用網址引用促銷公司(即www.companyxyz.com而不是XYZ公司)時,我的正則表達式會捕獲“ .com”,而我嘗試捕獲的其余短語-但是而不是“ www.companyxyz”部分。
這是我的正則表達式方法:
public string ExtractCompensationLine(string message)
{
string compensationLine = string.Empty;
string messageLine = Regex.Replace(message, "[\n\r\t]", " ");
string leftPrefix = @"\.((\w|\s|\d|\,)+";
string rightPrefix = @"(\w|\s|\d|\,)+\.)";
string[] phrases =
{
@"has been compensated",
@"we were also paid",
@"has been previously compensated",
@"currently being compensated",
@"the company has compensated",
@"has agreed to be compensated",
@"have been compensated up to",
@"dollars from a third party",
@"the company will compensate us"
};
foreach (string phrase in phrases)
{
string pattern = leftPrefix + phrase + rightPrefix;
Regex compensationRegex = new Regex(pattern, RegexOptions.IgnoreCase);
Match match = compensationRegex.Match(messageLine);
if (match.Success)
{
compensationLine += match.Groups[1].Value;
}
}
return compensationLine;
}
因此,正則表達式從句子的第一個單詞捕獲整個短語(通過查找句子的前一個句號,直到句子的最后一個句號。但是這些網址對我的正則表達式不利。
如果我正確地理解了您的問題,給定一個包含給定短語之一的句子,則您希望從該句子的開頭到其結尾或行尾。 您面臨的挑戰是找到要匹配的句子之前的句子結尾。 因此,您需要匹配“。”(句號后跟空白)。然后匹配其余部分。
我不明白為什么您會使用“(\\ w | \\ s | \\ d | \\,)”而不是“。”。 它不會給出我上面描述的結果,但是我將保持原樣,僅關注您描述的問題。
所以試試這個:
leftPrefix = @"(\.*\s+)*?((\w|\d|\,)+";
(。* \\ s +)*:匹配任何字符,后跟一個句點,后跟空白。
由於我使用括號將這個新的子表達式分組,因此您將擁有一個新的捕獲組,這意味着您需要使用Match對象的Captures集合,而不是Value。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.