【问题标题】:C# How can I detect a variable contains a comma delimited list of integers?C#如何检测包含逗号分隔的整数列表的变量?
【发布时间】:2016-10-24 16:03:19
【问题描述】:

是否有任何简单的方法来检测字符串变量是由逗号分隔的整数组成,还是单个整数?

以下是一些变量示例,以及我期望的结果:

var test1 = "123,456,489";
var test2 = "I, for once, do not know";
var test3 = "123,abc,987";
var test4 = "123";
var test5 = "1234,,134";


Test1 would be true. 
Test2 would be false. It contains alpha characters
Test3 would be falce. It contains alpha characters
Test4 would be true.  It not delimited, but still valid since its an integer.
Test4 would be false.  The second item is null / empty.

我想我可以用正则表达式攻击它,但我想先在这里发布问题,以防我缺少 C# 中的一些内置功能。

【问题讨论】:

  • 没有内置的。正则表达式听起来像是赢家。
  • 你可以用逗号分割字符串,然后将单独的分割转换为 int
  • String.Split()Int32.TryParse() 上的结果应该可以做到。

标签: c# integer comparison comma


【解决方案1】:

你可以这样做:

int foo;  // Ignored, just required for TryParse()
bool isListOfInts = testString.Split(',').All(s => int.TryParse(s, out foo));

【讨论】:

  • @rory.ap 这怎么不是我做的?您会看到结果是bool
  • 我选择了这个答案,因为它适合我的需要。下面的正则表达式同样有效,但有时我无法理解正则表达式模式。
【解决方案2】:

这是一个正则表达式示例:

string pattern = @"^\d+(,\d+)*$";
string input = "123,456,489";
bool isMatch = Regex.IsMatch(input, pattern);

【讨论】:

    【解决方案3】:
    int outInt;
    bool isListOfInts = !variablename.Split(",").Any(x=>!int.TryParse(x, outInt));
    

    【讨论】:

      猜你喜欢
      • 2018-03-21
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 2015-05-26
      相关资源
      最近更新 更多