c# - C# 中的 Swift MT940 解析器
问题描述
如何使用 C# 解析 MT940 快速消息?
以下是我必须解析的消息:
:20:MT940-1411201901
:25:1234567837710016
:28C:008/201
:60F:C171224SAR145597,13
:61:2107221722D17000,NCHK219120//14218-102431Abnamb
:61:2107221722D17000,NCHK219120//14218-102431Abnamb VSP
:62F:C291124SAR145597,13
我怎么能意识到这一点?
解决方案
尝试如下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.txt";
static void Main(string[] args)
{
MT940 mt940 = new MT940(FILENAME);
}
}
public class MT940
{
const string TAG_PATTERN = @"^:(?'tag'[^:]+):(?'value'.*)";
public string senderReference { get; set; } //code 20
public string authorisation { get; set; } // tag 25
public string messageIndexTotal { get; set; } //tag 28D
public Currency openingBalance { get; set; } //60F
public string firstTransaction { get; set; } //61
public string secondTransaction { get; set; } //61
public Currency closingBalance { get; set; } //62F
public MT940(string filename)
{
StreamReader reader = new StreamReader(filename);
string line = "";
int transactionCount = 0;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith(":"))
{
Match match = Regex.Match(line, TAG_PATTERN);
string tag = match.Groups["tag"].Value;
string value = match.Groups["value"].Value;
switch (tag)
{
case "20":
senderReference = value;
break;
case "25":
authorisation = value;
break;
case "28C":
messageIndexTotal = value;
break;
case "60F":
openingBalance = new Currency(value);
break;
case "61":
if (++transactionCount == 1)
{
firstTransaction = value;
}
else
{
secondTransaction = value;
}
break;
case "62F":
closingBalance = new Currency(value);
break;
default:
break;
}
}
}
}
}
public class Currency
{
const string BALANCE_PATTERN = @"^(?'credit_debit'.)(?'date'.{6})(?'country_code'.{3})(?'amount'.*)";
static CultureInfo culture = CultureInfo.GetCultureInfoByIetfLanguageTag("da");
public DateTime date { get; set; }
public string currencyCode { get; set; }
public decimal amount { get; set; }
public Currency(string input)
{
Match match = Regex.Match(input, BALANCE_PATTERN);
string credit_debit = match.Groups["credit_debit"].Value;
string dateStr = match.Groups["date"].Value;
date = DateTime.ParseExact(dateStr, "yyMMdd", CultureInfo.InvariantCulture);
currencyCode = match.Groups["country_code"].Value;
string amountStr = match.Groups["amount"].Value;
amount = decimal.Parse(amountStr, culture);
amount *= credit_debit == "D" ? -1 : 1;
}
}
}
推荐阅读
- javascript - 一个值在 React 中的原始值后面
- c - 为什么在 Windows 上打印这个宽字符串会崩溃?
- python - 在windows上安装cleverHans
- html - 导航栏超出了 Chrome 的正文
- javascript - mediaelement 在 2 秒后不显示播放视频。在角度 8
- firebase - Firebase 电子邮件验证立即过期
- python - Selenium 错误:无法找到一组匹配的功能
- python - 具有更快 rcnn 模型的低 Map
- windows - 如何从 docker 容器中归档以托管在 Windows 容器中
- typescript - 需要打字稿承诺帮助