使用LINQ检查字符串中是否至少包含一个数字

Job*_*Joy 68 c# linq

我想知道如果字符串中包含任何数字字符,最简单和最短的LINQ查询将返回true.

Fre*_*örk 168

"abc3def".Any(c => char.IsDigit(c));
Run Code Online (Sandbox Code Playgroud)

更新:正如@Cipher指出的那样,它实际上可以更短:

"abc3def".Any(char.IsDigit);
Run Code Online (Sandbox Code Playgroud)

  • @ cihata87确保在代码文件的顶部添加了`using System.Linq;`. (6认同)

Jar*_*Par 15

试试这个

public static bool HasNumber(this string input) {
  return input.Where(x => Char.IsDigit(x)).Any();
}
Run Code Online (Sandbox Code Playgroud)

用法

string x = GetTheString();
if ( x.HasNumber() ) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

  • 或者只是`input.Any(x => Char.IsDigit(x));` (4认同)

小智 8

或可能使用正则表达式:

string input = "123 find if this has a number";
bool containsNum = Regex.IsMatch(input, @"\d");
if (containsNum)
{
 //Do Something
}
Run Code Online (Sandbox Code Playgroud)