c# - 解析 C# 中的 2 个数字除以减号

标签 c# string-parsing

我必须解析一个字符串。它包含一个或两个数字。

它可以有 3 个来源。

  1. {number1}-{number2}
  2. {number1}-
  3. -{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/

相关文章:

c# - C#中 "string @namespace"是什么意思?

c# - EF 7 为 DateTime 列设置初始默认值

c# - 从另一个表单访问字符串

c# - 如何在 C# API 中返回 JSON

java - Java 从平面文件中读取多条记录

java.text.ParseException : Unparseable date: "531772200000"

loops - 在文件夹中搜索包含服务器名称和扩展名的文件,然后选择最后修改的文件,并在文件名中获取日期

c# - 如何为不同的子类实现接口(interface)的多个实例?

split - OCaml是否具有像Python这样的String.split函数?

c# - 在 C# 中评估特殊表达式