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

本文关键字:分隔 整数 列表 包含逗 是否 何检测 检测 变量 | 更新日期: 2023-09-27 18:14:34

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

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

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 foo;  // Ignored, just required for TryParse()
bool isListOfInts = testString.Split(',').All(s => int.TryParse(s, out foo));

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

string pattern = @"^'d+(,'d+)*$";
string input = "123,456,489";
bool isMatch = Regex.IsMatch(input, pattern);
  • 查询"123,456,489"的结果
  • "123,abc,987"的结果
  • "123"的结果
  • 查询"1234,,134"的结果
int outInt;
bool isListOfInts = !variablename.Split(",").Any(x=>!int.TryParse(x, outInt));