我刚刚进入FSharp而且我已经挣扎了很长一段时间,因为我无法理解为什么我没有在比赛声明中得到我预期的结果。
根据消息编号,我需要将数组中的某些值(拆分)与我想要返回的记录上的字段相匹配。
let UNMATCHED = "UNMATCHED"
let T0200 = "T0200" ;; let R0200 = "R0200"
let matchTypes = [| { MessageType = T0200; Regex = REGEX_T0200 }
; { MessageType = R0200; Regex = REGEX_R0200 }
...
let messageInfo (matchType:MatchType, line:string) =
let matching = Regex.Match(line, REGEX_DATA)
let splits = matching.Value.Replace("[","").Replace("]","").Split('|')
let showSplit (x:string[]) = "[" + String.Join(";",x) + "]"
let info =
Console.WriteLine("matching against: " + matchType.MessageType)
match matchType.MessageType with
| T0200 ->
{ MessageType = T0200; CustomerID = splits.[1]; CustomerName = "";
ItemID = splits.[2]; ItemDescription = "" }
| R0200 ->
{ MessageType = R0200; CustomerID = splits.[1]; CustomerName = splits.[2];
ItemID = splits.[5]; ItemDescription = splits.[6] }
...
| UNMATCHED -> { MessageType = UNMATCHED; CustomerID = ""; CustomerName = "";
ItemID = ""; ItemDescription = "" }
| _ -> { MessageType = UNMATCHED; CustomerID = ""; CustomerName = "";
ItemID = ""; ItemDescription = "" }
Console.WriteLine("messageInfo: {0}", (matchType, showSplit splits, info))
info
然而,这似乎不起作用,从下面的输出中,我得到了T0200的预期结果,但是对于R0200,字段的映射与数组中的字段不匹配 - 即。它似乎使用与T0200语句相同的数组索引。我对所有其他后续消息都有完全相同的问题。
matching against: T0200
messageInfo: ({MessageType = "T0200";
Regex = "\sT0200\[([\w\s]*\|)*[\w\s]*\]";}, [3;000008757051;1401], {MessageType = "T0200";
CustomerID = "000008757051";
CustomerName = "";
ItemID = "1401";
ItemDescription = "";})
matching against: R0200
messageInfo: ({MessageType = "R0200";
Regex = "\sR0200\[([\w\s]*\|)*[\w\s]*\]";}, [3;000008757051;Ricky Bobby;413792;0;1401;SNACKER;909;0], {MessageType = "R0200";
CustomerID = "000008757051";
CustomerName = "";
ItemID = "Ricky Bobby";
ItemDescription = "";})
我猜测我的匹配声明中的语法有问题 - 我做错了什么?
我在ubuntu上运行dotnet core 2.0.2
由于
答案 0 :(得分:5)
MessageType
是一个字符串,T0200
只是一个命名字符串值。当您尝试匹配T0200
时,它实际上将字符串绑定到T0200
,并始终进入match
的第一个分支。模式匹配语言不允许您匹配类似的值名称。您可以匹配有区别的联合案例,文字值和一些其他事物。请参阅here。