这是一个两步过程,因为正则表达式是文本解析器而不是分析器。但是话虽如此,正则表达式非常适合验证我们是否具有 5:5 数字模式,并且此正则表达式模式将确定我们是否具有该形状因子 \d\d\d\d\d:\d\d\d\d \d 对。如果未找到该外形尺寸,则匹配失败并且整个验证失败。如果有效,我们可以使用 regex/linq 解析出数字,然后检查其有效性。
此代码将在进行检查的方法中
var data = "00515:02151";
var pattern = @"
^ # starting from the beginning of the string...
(?=[\d:]{11}) # Is there is a string that is at least 11 characters long with only numbers and a ;, fail if not
(?=\d{5}:\d{5}) # Does it fall into our pattern? If not fail the match
((?<Values>[^:]+)(?::?)){2}
";
// IgnorePatternWhitespace only allows us to comment the pattern, it does not affect the regex parsing
var result = Regex.Matches(data, pattern, RegexOptions.IgnorePatternWhitespace)
.OfType<Match>()
.Select (mt => mt.Groups["Values"].Captures
.OfType<Capture>()
.Select (cp => int.Parse(cp.Value)))
.FirstOrDefault();
// Two values at this point 515, 2151
bool valid = ((result != null) && (result.First () < result.Last ()));
Console.WriteLine (valid); // True