我必须解析一个字符串.它包含一个或两个数字.
它可以有3个来自.
数字可能是负数.
例如:
现在更难的部分:
-100--200表示:number1 = -100,number2 = -200
-100-200-表示:抛出新的FormatException().它不是一个有效的字符串.
任何无法解析为2 ints的东西都会抛出一个formatexception(int.Parse会这样做,因此可以依赖它).
我需要一个解析器来解析它到两个int?-s(可空的整数).
每个字符串都有效(有意义)或无效(它没有意义).没有字符串可以表示两件事(至少我找不到一件事).
如果我得到2值,我希望它返回一个元组.
我纠结于ifs.
(编辑以从评论中添加更新的正则表达式)
看起来您可以使用Regex类来解决这个问题,因为您的语法是相当规则的并且结构如下:
var regex = new Regex(@"^(?<first>-?[\d.,]+)?-(?<second>-?[\d.,]+)?$");
var match = regex.Match(input);
if (match.Success)
{
int? a = match.Groups["first"].Success
? Int32.Parse(match.Groups["first"].Value)
: (int?)null;
int? b = match.Groups["second"].Success
? Int32.Parse(match.Groups["second"].Value)
: (int?)null;
}
Run Code Online (Sandbox Code Playgroud)