C#如何检测包含逗号分隔的整数列表的变量?

时间:2016-10-24 16:03:19

标签: c# integer comparison comma

有没有简单的方法来检测字符串变量是否设置了逗号分隔的整数或单个整数?

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

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#中有一些我缺少的内置功能。<​​/ p>

3 个答案:

答案 0 :(得分:2)

你可以这样做:

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

答案 1 :(得分:2)

这是一个正则表达式的例子:

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

答案 2 :(得分:0)

int outInt;
bool isListOfInts = !variablename.Split(",").Any(x=>!int.TryParse(x, outInt));