繁体   English   中英

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

[英]Extracting data from text using templates

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

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

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

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

我从来没有完全了解RegExp。 万一这确实是我要走的道路,我将做出新的努力。 :)

我会使用正则表达式:

第一个示例,如果您只有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:Action:This is my friggin format, now please read the status --> ...

Regex.Escape(userEntry)部分对于确保用户通过提交特殊字符(例如\\ 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然后您通过替换标签字符串来构建正则表达式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM