0

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

传入电子邮件的格式不同,例如,一些系统调用状态“状态:ZZZZZ”和一些“操作:ZZZZZ”。自由文本有时出现在状态之前和之后。状态代码将映射到我的系统解释,并且注释也是必需的。

此外,我希望格式会随着时间而改变,因此可配置的解决方案(可能由客户通过 Web 界面提供自己的模板)将是理想的。

该服务是使用 .NET C# MVC 3 构建的,但我会对一般策略以及任何特定的库/工具/方法感兴趣。

我从来没有完全了解过 RegExp。如果这确实是要走的路,我会做出新的努力。:)

4

1 回答 1

1

我会用正则表达式:

第一个例子,如果你只有Status: 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

第二个例子,如果你只有Status: ZZZZZAction: ZZZZZ- 类似的消息:

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 + ").*");

这将允许用户提交其格式,如Status:, or Action:, or This is my friggin format, now please read the status -->...

Regex.Escape(userEntry)部分对于确保用户不会通过提交特殊字符(如\, ?, *... )来破坏您的正则表达式很重要


要知道用户是在格式文本之前还是之后提交状态值,您有几种解决方案:

  • 您可以询问用户他的状态值在哪里,然后相应地构建您的正则表达式:

    if (statusValueIsAfter) {
        // Example: "Status: Closed"
        regexPattern = @"(?<=Status: ).*";
    } else {
        // Example: "Closed:Status"
        regexPattern = @".*(?=:Status)";  // We use here a positive look-AHEAD
    }
    
  • 或者您可以更聪明一些,并为用户条目引入一个标签系统。例如,用户提交Status: <value><value>=The status您通过替换标签字符串来构建正则表达式。

于 2011-11-11T12:29:15.947 回答