c#regex匹配字符串比较(查找最小值)
本文关键字:查找 最小值 比较 字符串 c#regex | 更新日期: 2023-09-27 18:21:08
我完全不知道如何实现这一点。基本上,我想在METAR报告中找到上限。天花板是最小的碎层或阴天。
我目前有这个(无论如何都不多):
MatchCollection matches = Regex.Matches(modify, @"(BKN|OVC)([0-9]{3})");
foreach (Match match in matches)
{
foreach (Capture capture in match.Captures)
{
// compare broken and overcast layers to find smallest value and set as the ceiling
Console.WriteLine(capture.Value);
}
}
基本上,这会在METAR字符串中搜索BKN或OVC层并将其吐出。以METAR读数为例:
PANC 040553Z 17013G24KT 280V360 2SM FEW050 BKN019 BKN008 OVC005 14/M07 A2999 RMK AO2 SLP156 SH DSNT W-N T01390067 10167 20139 53002
我当前拥有的代码将吐出BKN019、BKN008和OVC005。我需要做的是选择这些值中最小的一个(在这种情况下,它将是OVC005)。
如果有人能帮我,我将不胜感激。
尝试使用捕获组:
// (?<number> names the group that captures the number value
var matches = Regex.Matches(modify, @"(BKN|OVC)(?<number>[0-9]{3})");
// cast to IEnumerable<Match>()
var smallest = matches.Cast<Match>()
// order by the parsed number group
// Added `.Value` to make this work
.OrderBy(m => int.Parse(m.Groups["number"].Value))
// Select the string value
.Select(m => m.Value)
// take the first (the smallest)
.FirstOrDefault();
如果最小值为null
,则未找到匹配的
基本上,您想要做的是跟踪到目前为止找到的最底层,然后检查每个正则表达式匹配是否比以前更低:
int lowestLayer = int.MaxValue;
MatchCollection matches = Regex.Matches(modify, @"(BKN|OVC)([0-9]{3})");
foreach (Match match in matches)
{
foreach (Capture capture in match.Captures)
{
int layer = int.Parse(capture.Value.Substring(3));
if (layer < lowestLayer)
lowestLayer = layer;
Console.WriteLine(capture.Value);
}
}
如果我理解正确,你想为最小的第二组完成整个捕获。
matches.OfType<Match>()
.Select(m => new { Capture = m.Groups[0], Number = Int32.Parse(m.Groups[2]) })
.OrderBy(m => m.Number)
.Select(m => m.Capture)
.FirstOrDefault();
Linq
是您的好友
记住using System.Linq
MatchCollection matches = Regex.Matches(modify, @"(BKN|OVC)([0-9]{3})");
var first = (
from x in matches.OfType<Match>()
orderby int.Parse(x.Groups[2].Value)
select x.Value
).FirstOrDefault();