C# 使用模板从文本中提取数据

C# 使用模板从文本中提取数据,c#,parsing,email,information-extraction,C#,Parsing,Email,Information Extraction,我正在构建一个web服务,它接收来自许多CRM系统的电子邮件。电子邮件通常包含文本状态,例如“已收到”或“已完成”,以及自由文本评论 传入电子邮件的格式不同,例如,一些系统将状态称为“status:ZZZZZ”,而另一些系统则称为“Action:ZZZZZ”。自由文本有时出现在状态之前,有时出现在状态之后。状态代码将映射到我的系统解释,并且需要注释 此外,我希望格式会随着时间的推移而改变,因此一个可配置的解决方案是理想的,客户可以通过web界面提供自己的模板 该服务是使用.NETC#MVC3构建

我正在构建一个web服务,它接收来自许多CRM系统的电子邮件。电子邮件通常包含文本状态,例如“已收到”或“已完成”,以及自由文本评论

传入电子邮件的格式不同,例如,一些系统将状态称为“status:ZZZZZ”,而另一些系统则称为“Action:ZZZZZ”。自由文本有时出现在状态之前,有时出现在状态之后。状态代码将映射到我的系统解释,并且需要注释

此外,我希望格式会随着时间的推移而改变,因此一个可配置的解决方案是理想的,客户可以通过web界面提供自己的模板

该服务是使用.NETC#MVC3构建的,但我对一般策略以及任何特定的库/工具/方法都感兴趣

我对RegExp从来都不太了解。我将做出新的努力,以防这确实是一条路。:)

我会选择正则表达式:

第一个示例,如果您只有类似于
状态:ZZZZZ
的消息:

String status = Regex.Match(@"(?<=Status: ).*");
// Explanation of "(?<=Status: ).*" :
// (?<=       Start of the positive look-behind group: it means that the 
//            following text is required but won't appear in the returned string
// Status:    The text defining the email string format
// )          End of the positive look-behind group
// .*         Matches any character
String status = Regex.Match(@"(?<=(Status|Action): ).*");
// We added (Status|Action) that allows the positive look-behind text to be 
// either 'Status: ', or 'Action: '

现在,如果您想让用户提供自己的格式,您可以提出如下建议:

String userEntry = GetUserEntry(); // Get the text submitted by the user
String userFormatText = Regex.Escape(userEntry);
String status = Regex.Match(@"(?<=" + userFormatText + ").*");
  • 或者你可以更聪明一些,为用户输入引入一个标签系统。例如,用户提交
    状态:
    =状态
    ,然后通过替换标记字符串来构建正则表达式


  • 请更具体一些。显示输入数据格式示例,您尝试过的代码,编写您期望的问题。如果没有…那么我会回答-学习RegExp:)非常感谢您提供的有用提示!这会让我有一个好的开始!有没有办法提取多个值?e、 g.如果状态:和操作在同一消息中。
    if (statusValueIsAfter) {
        // Example: "Status: Closed"
        regexPattern = @"(?<=Status: ).*";
    } else {
        // Example: "Closed:Status"
        regexPattern = @".*(?=:Status)";  // We use here a positive look-AHEAD
    }