正则表达式匹配字典键
本文关键字:字典 正则表达式 | 更新日期: 2023-09-27 18:10:05
我正在扩展我之前问的问题。
在我解释之前,这里是我的c#代码:static Dictionary<string, string> phenom = new Dictionary<string, string>
{
{"-", "Light"},
{"''+", "Heavy"},
{"'bVC'b","In the Vicinity"},
// descriptor
{"MI","Shallow"},
{"PR","Partial"},
{"BC","Patches"},
{"DR","Low Drifting"},
{"BL","Blowing"},
{"SH","Showers"},
{"TS","Thunderstorm"},
{"FZ","Freezing"},
// precipitation
{"DZ","Drizzle"},
{"RA","Rain"},
{"SN","Snow"},
{"SG","Snow Grains"},
{"IC","Ice Crystals"},
{"PL","Ice Pellets"},
{"GR","Hail"},
{"GS","Small Hail/Snow Pellets"},
{"UP","Uknown Precipitation"},
// obscuration
{"BR","Mist"},
{"FG","Fog"},
{"FU","Smoke"},
{"VA","Volcanic Ash"},
{"DU","Widespread Dust"},
{"SA","Sand"},
{"HZ","Haze"},
{"PY","Spray"},
// other
{"PO","Well-Developed Dust/Sand Whirls"},
{"SQ","Squalls"},
{"FC","Funnel Cloud Tornado Waterspout"},
{"SS","Sandstorm"},
{"DS","Duststorm"}
};
public static string Process(String metar)
{
metar = Regex.Replace(metar, "(?<=A[0-9]{4}).*", "");
StringBuilder _string = new StringBuilder();
var results = from result in phenom
where Regex.Match(metar, result.Key, RegexOptions.Singleline).Success
select result;
foreach (var result in results)
{
if (result.Key == "DZ" || result.Key == "RA" || result.Key == "SN" || result.Key == "SG" || result.Key == "PL")
{
switch (result.Key)
{
case "+":
_string.Append("Heavy ");
break;
case "-":
_string.Append("Light");
break;
case "VC":
_string.Append("In the Vicinity ");
break;
default:
break;
}
}
_string.AppendFormat("{0} ", result.Value);
}
return _string.ToString();
}
基本上,此代码解析机场METAR天气报告中的天气现象。以下面的METAR为例:
KAMA 230623Z AUTO 05016KT 7SM +TSRAGR FEW070 BKN090 OVC110 16/14 A3001RMK AO2 PK WND 06026/0601 LTG DSNT E-SW RAB04 TSB02E17 P0005 T01560144
注意+TSRAGR…这是我想着重讲的部分。我目前的代码工作得很好……但离我真正想要的还差得远。它吐出的是:"大雷雨冰雹"。
实际的解码略有不同。参考本手册(见第5页)
强度指标(+和-)总是出现在第一次降水之前。在上述METAR中,它将是RA。所以,理想情况下,它应该吐出"雷暴大雨冰雹"。然而,事实并非如此。还有一些时候,这种现象没有那么强烈……有时可能只有-RA,在这种情况下应该只返回"Light Rain"。
还要注意的是,正如我引用的手册所说,强度标识符没有用IC, GR, GS或UP降水类型编码,这解释了我在附加强度之前检查键值的尝试,但失败了。
如果有人能告诉我如何在正确的位置添加强度标识符,我将不胜感激。
TL;博士…基本上,我使用一些代码逻辑来决定将前缀放在字典列表中特定项之前的位置。
考虑到代码的结构,我建议对输入字符串进行预解析,将强度指标"移动"到它们不修改的术语之后,这样单词就会以最有意义的顺序出现。
然后,我可能会考虑在你的字典中添加一些键,以涵盖每种降水类型的+/-版本,这些降水类型可以有一个强度指示器,这样你的整体代码就简化了。