我必须解析一个字符串。它包含一个或两个数字。
它可以有 3 个来源。
- {number1}-{number2}
- {number1}-
- -{number2}
数字可以是负数。
例如:
- 100-200 表示:数字 1 = 100,数字 2 = 200
- -100 表示:number1 = null,number2 = 100
- 200- 表示:number1 = 200, number2 = null
现在是更难的部分:
- -100-200 表示:number1 = -100, number2 = 200
- -100- 表示:number1 = -100, number2 = null
- --100 表示:number1 = null, number2 = -100
- 100--200 表示:number1 = 100, number2 = -200
-100--200 表示:number1 = -100, number2 = -200
-100-200- 表示:抛出新的 FormatException()。它不是有效的字符串。
任何不能解析为 2 int 的东西都会抛出一个 formatexception(int.Parse 这样做,所以它可以依赖)。
我需要一个解析器来将它解析为两个整数? -s(可为空的整数)。
每个字符串要么有效(有意义),要么无效(没有意义)。没有字符串可以表示两件事(至少我没有找到)。
如果我获取 2 值,我希望它以元组形式返回。
我陷入了如果。
最佳答案
(编辑以从评论中添加更新后的正则表达式)
看起来你可以使用 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;
}
关于c# - 解析 C# 中的 2 个数字除以减号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9538048/