解决这个问题的一种方法是:
- 使用 RegEx 返回
(x,y) 模式的匹配项。
- 使用扩展方法提取
x和y。
- 使用
decimal.TryParse(..)方法检查x和y是否为decimal类型。
- 检查输入字符串是否包含所需模式以外的其他内容。
private bool IsValidInput(string input)
{
var pattern = @"\((.*?)\s?,\s?(.*?)\)";
var xpatt = @"\s+\(|\s+\)|\,\(|\)\,|\)\s+|\({2,}|\){2,}|^\)\(|\)\($";
var q = Regex.Matches(input, pattern)
.Cast<Match>()
.SelectMany(x => x.Groups.Cast<Group>()
.Skip(1))
.Select(x => x.Value);
return !Regex.IsMatch(input, xpatt)
&& q.Count() > 0
&& input.Replace(" ","").Length
== (input.Count(x => x == '(' || x == ')' || x == ',')
+ q.Sum(x => x.Length))
&& q.All(x => decimal.TryParse(x, out _));
}
所以,函数返回:
(1.01, 3.21)(3.01, 4.51)(2.1, 5.6) => true
(abc, 3.21)(3.01, 4.51)(2.1, 5.6) => false
(3.21)(3.01, 4.51)(2.1, 5.6) => false
1.01, 3.2 13.01, 4.51 2.1, 5.6 => false
1.01, 3.21)(3.01, 4.51)(2.1, 5.6) => false
(1.01, 3.21)(3.01, 4.51)(2.1, 5.6 => false
1.01, 3.21)3.01, 4.51)2.1, 5.6) => false
(1.01, 3.21)3.01, 4.51(2.1, 5.6) => false
(1.01, 3.21)abc(3.01, 4.51)(2.1, 5.6) => false
(1.01, 3.21)(3.01, 4.51)abc(2.1, 5.6) => false
abc(1.01, 3.21)(3.01, 4.51)(2.1, 5.6) => false
(1.01, 3.21)(3.01, 4.51)(2.1, 5.6)abc => false