我正在开发asp.net mvc。我正在尝试扫描或解析航班电子机票,以提取诸如确认号、航班号、航空公司名称、旅行开始日期和结束日期等信息。首先,我从我的电子邮件中阅读邮件,在那里我可以使用IMAP找到我的电子客票,例如,
using (Imap imap = new Imap())
{
imap.Connect("imap.gmail.com", 993, true);
imap.Login("***@gmail.com", "XXXX");
imap.SelectInbox();
List<long> uids = imap.Search(Flag.All);
foreach (long uid in uids)
{
string eml = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(eml);
....
....
}
}实际上我的困难部分出现了,有很多航空公司都退出了,每个航空公司都遵循自己的设计或规范的电子客票外观,他们可能每3个月重新更新他们的电子客票,或者他们可以对每个航班的机票有自己的风格。所以这不是很好的标准,写下这样的条件
If AmericanAirlines:
....do stuff for AA....
Else If SouthAirlines:
....do stuff for AA....
..
..首先,我教会了如何使用HtmlAgilityPack解析电子客票,因为所有电子客票都是使用HTML语言设计或准备的,所以我可以使用这个库来解析DOM元素并从中提取信息。但它会变得非常复杂,我需要写解析代码为航空公司机票。因此我决定使用正则表达式来匹配确认号和航空公司名称,如下所示:
string code = "";
Match match = Regex.Match(email.Text.Replace("*", ""), @"\s*((Record\s*Locator)|(Confirmation\s*[a-zA-Z]{0,4})|(AIR\s*Confirmation)|(Flight\s*Confirmation))(\s*)(\#*)(\s*)(\:*)(\s*)[A-Z0-9]{6}", RegexOptions.IgnoreCase);
if (match.Success)
{
string s = Regex.Replace(match.Value, @"\\r\\n", "").Trim();
code = s.Substring(s.Length - 6);
if (!confirmcodes.Any(m => m == code))
confirmcodes.Add(code);
}
string airline = "";
Match airlinematch = Regex.Match(email.Text.Replace("*", ""), @"\s*(.*)\s*((Air\s*lines\s*)|(Air\s*ways\s*))", RegexOptions.IgnoreCase);
if (airlinematch.Success)
{
string s = Regex.Replace(airlinematch.Value, @"\\r\\n", "").Trim();
airline = airlinematch.Groups[0].Value;
}上述条件可能只满足某些航空公司,如果机票是以非常不寻常的方式设计的,条件将被打破。因此,请指导我更好的策略,以扫描适合任何类型的航空公司的机票的航班电子机票。提前谢谢。
发布于 2013-12-10 04:31:33
我将使用更灵活的两步系统:
步骤1:查找并提取整个信息
我会使用解析器来定位信息。我会要求解析器将此信息提取为文本。
HtmlParser parser = new HtmlParser();
parser.loadHtml(...);
String information = parser.select('div#information').toString();Step2:分析提取的信息
在XML文件的帮助下,我会在其中放入用于提取所需信息的各种正则表达式。
我的文件将如下所示:
<regexes>
<regex name="AA Airlines">
<name><![CDATA[AA\s+\w+]]></name>
<seat><![CDATA[\d+]]></seat>
...
</regex>
<regex name="South Airlines">
<name><![CDATA[South\s*[a-z]]]></name>
<seat><![CDATA[\d{2}-\d{4}-\d+]]></seat>
...
</regex>
...
</regexes>然后,在我的C#代码中,我将解析上面的小配置文件,并根据每个“变体”检查我的information。稍后,如果出现新的变体,我只需更新我的小配置文件。
https://stackoverflow.com/questions/20469349
复制相似问题