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

我想知道最简单和最短的 LINQ 查询是返回真,如果一个字符串包含任何数字字符在其中。

70878 次浏览

试试这个

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

用法

string x = GetTheString();
if ( x.HasNumber() ) {
...
}
"abc3def".Any(c => char.IsDigit(c));

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

"abc3def".Any(char.IsDigit);

或可能使用正则表达式:

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

这样吧:

bool test = System.Text.RegularExpressions.Regex.IsMatch(test, @"\d");
string number = fn_txt.Text;   //textbox
Regex regex2 = new Regex(@"\d");   //check  number
Match match2 = regex2.Match(number);
if (match2.Success)    // if found number
{  **// do what you want here**
fn_warm.Visible = true;    // visible warm lable
fn_warm.Text = "write your text here ";   /
}